Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can simply use a Vec:

use serde::{Serialize, Deserialize};

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

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

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

    for data in datas.iter() {
        println!("{:#?}", data);
    }

    Ok(())
}

If you wish, you could also use transparent:

#[derive(Serialize, Deserialize, Debug)]
#[serde(transparent)]
struct Foos {
    foos: Vec<Foo>,
}

let foos: Foos = serde_json::from_str(data)?;

This allows to encapsulate your data with your type.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...