锈与Serde JSON反序列化示例? [英] Rust & Serde JSON deserialization examples?
问题描述
我试图弄清楚如何使用Serde将JSON反序列化为结构.例如,serde_json的自己的文档上的示例JSON包含以下内容数据:
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"
]
}
现在,如果我们假设上面的数据在变量"input"和下面的代码中:
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();
...结构Data
应该是什么样子?
... what should struct Data
look like?
推荐答案
大多数标准数据结构都是可序列化的,因此以下结构应该可以工作:
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
}
如果输入中可能缺少某些字段,则对应的结构字段应为Option<T>
而不是T
.
If some of the fields in input may be absent, then the corresponding structure fields should be Option<T>
instead of just T
.
请注意,由于serde支持重命名注释,因此可以使用更鲁棒"的方式来命名字段,即snake_case.
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.
这篇关于锈与Serde JSON反序列化示例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!