[英]Deserializing different data structures with rust serde
I am trying to deserialize JSON that is received from Web API and has some unnecessarily deep structure.我正在尝试反序列化从 Web API 收到的 JSON 并且具有一些不必要的深度结构。
With serde
, is it possible to deserialize JSON like:使用serde
,是否可以像反序列化 JSON 一样:
{
"unnecessarily": {
"deep": {
"structure": {
"data1": 0
}
}
},
"data2": 0
}
to rust struct:到 rust 结构:
struct Data {
data1: usize,
data2: usize,
}
without manually implementing Deserialize
?无需手动实现Deserialize
?
If it is impossible, are there any other suitable crates?如果不可能,还有其他合适的箱子吗?
You can use serde's derive
macro to generate implementations of Serialize
and Deserialize
traits您可以使用serde 的derive
宏来生成Serialize
和Deserialize
序列化特征的实现
use serde::Deserialize;
#[derive(Deserialize)]
struct Data {
data1: usize,
data2: usize,
}
If the JSON structure is not known ahead of time, you can deserialize to serde_json::Value
and work with this如果事先不知道 JSON 结构,您可以反序列化为serde_json::Value
并使用它
use serde_json::{Result, Value};
fn example() -> Result<()> {
let data = r#"
{
"unnecessarily": {
"deep": {
"structure": {
"data1": 0
}
}
},
"data2": 0
}"#;
let v: Value = serde_json::from_str(data)?;
let data1 = v["unnecessarily"]["deep"]["structure"]["data1"].as_i64()?;
Ok(())
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.