4

According to the JSON specification, the root of a JSON document can be either an object or an array. The first case is easily deserialized by serde_json using a struct

#[derive(Deserialize)] struct Person { first_name: String, last_name: String, } fn main() { let s = r#"[{"first_name": "John", "last_name": "Doe"}]"#; // this will break because we have a top-level array let p: Person = serde_json::from_str(s).unwrap(); println!("Name: {} {}", p.first_name, p.last_name); } 

However I cannot find any documentation on how to deserialize an (unnamed) array of structs.

1
  • 2
    What did you try? What was the result? Commented Aug 3, 2017 at 10:33

1 Answer 1

8

We just have to declare the result to be a vector of that type:

let p: Vec<Person> = serde_json::from_str(s).unwrap(); println!("Name: {} {}", p[0].first_name, p[0].last_name); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.