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
  • 9,621
  • 5
  • 41
  • 62
matthias
  • 2,161
  • 15
  • 22

1 Answers1

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);
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
matthias
  • 2,161
  • 15
  • 22