Rust & Serde JSON deserialization examples?

让人想犯罪 __ 提交于 2019-12-08 14:46:00

问题


I'm trying to figure out how to deserialize JSON into a structure using Serde. For instance, the example JSON on serde_json's own documentation contains the following data:

{
    "FirstName": "John",
    "LastName": "Doe",
    "Age": 43,
    "Address": {
        "Street": "Downing Street 10",
        "City": "London",
        "Country": "Great Britain"
    },
    "PhoneNumbers": [
        "+44 1234567",
        "+44 2345678"
    ]
}

Now, if we assume that the above data is in a variable "input" and the following piece of code:

let deserialized_data: Data = serde_json::from_str(input).unwrap();

... what should struct Data look like?


回答1:


Most of the standard data structures are serializable, so the following structures should work:

#[derive(Serialize, Deserialize)]
struct Data {
    FirstName: String,
    LastName: String,
    Age: u32,
    Address: Address,
    PhoneNumbers: Vec<String>
}

#[derive(Serialize, Deserialize)]
struct Address {
    Street: String,
    City: String,
    Country: String
}

If some of the fields in input may be absent, then the corresponding structure fields should be Option<T> instead of just T.

Note that it is possible to name fields in a more "Rusty" manner, i.e. snake_case, because serde supports renaming annotations:

#[derive(Serialize, Deserialize)]
struct Address {
    #[serde(rename="Street")]
    street: String,
    #[serde(rename="City")]
    city: String,
    #[serde(rename="Country")]
    country: String
}

This issue is also relevant to fields renaming.



来源:https://stackoverflow.com/questions/33251881/rust-serde-json-deserialization-examples

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