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

|▌冷眼眸甩不掉的悲伤 提交于 2019-11-26 09:59:31

问题


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 structs 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?


回答1:


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();
}


来源:https://stackoverflow.com/questions/44610594/how-can-i-deserialize-json-with-a-top-level-array-using-serde

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!