Deserializing JSON root array with serde_json

Viewed 2421

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 Answers
Related