简体   繁体   中英

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

I have a some JSON data that is returned from a web service. The JSON is a top-level array:

[
    {
        "data": "value1"
    },
    {
        "data": "value2"
    },
    {
        "data": "value3"
    }
]

Using serde_derive to make struct s I can can deserialize the data contained within the array, however, I am unable to get Serde to deserialize the top-level array.

Am I missing something, or can Serde not deserialize top level-arrays?

You can use a Vec :

extern crate serde;
extern crate serde_json;

#[macro_use]
extern crate serde_derive;

use serde_json::Error;

#[derive(Serialize, Deserialize, Debug)]
struct Foo {
    data: String,
}

fn typed_example() -> Result<(), Error> {
    let data = r#"[
        {
            "data": "value1"
        },
        {
            "data": "value2"
        },
        {
            "data": "value3"
        }
    ]"#;

    let array: Vec<Foo> = serde_json::from_str(data)?;

    for elem in array.iter() {
        println!("{:?}", elem);
    }
    Ok(())
}

fn main() {
    typed_example().unwrap();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM