How do I deserialize a JSON array without needing

2019-09-01 15:03发布

问题:

This question already has an answer here:

  • How can I deserialize JSON with a top-level array using Serde? 1 answer

I want to deserialize the following JSON:

[
  {
    "name": "one",
    "path": "/path/to/one"
  },
  {
    "name": "two",
    "path": "/path/to/two"
  },
  {
    "name": "three",
    "path": "/path/to/three"
  }
]

Into a Vec<Worskpace>. Workspace is defined below:

#[derive(Serialize, Deserialize)]
struct Workspace {
    name: String,
    path: String,
}

Is there a way to do that without having to do something like:

#[derive(Serialize, Deserialize)]
struct Workspacesss {
    values: Vec<Workspace>,
}

回答1:

Just deserialize the vector directly:

let workspaces = serde_json::from_str::<Vec<Workspace>>(input);