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.

dtolnay
  • 7,846
  • 1
  • 42
  • 56
matthias
  • 2,121
  • 14
  • 22

1 Answers1

6

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);
Shepmaster
  • 326,504
  • 69
  • 892
  • 1,159
matthias
  • 2,121
  • 14
  • 22