#[serde(rename)]
似乎是正确的选择,但文档没有说明是否可行或如何做。
这个JSON对象:
{
"name" : "myobject"
"info" :
{
"counter" : "3"
"foo" : "bar"
}
}
相应的 flat Rust结构应为:
#[derive(Deserialize)]
struct Object {
name: String,
#[serde(rename="info.counter")] // wrong syntax here !!
count: i32,
#[serde(rename="info::foo")] // neither this works
foo: String,
}
答案 0 :(得分:4)
没有内置的方法可以使用属性执行此操作,但是您可以为Deserialize
类型编写自己的Object
impl,先将其反序列化为某些中间帮助器表示形式,然后将数据重新排列为所需的结构。
#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate serde_json;
use serde::{Deserialize, Deserializer};
#[derive(Debug)]
struct Object {
name: String,
count: i32,
foo: String,
}
impl<'de> Deserialize<'de> for Object {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>
{
#[derive(Deserialize)]
struct Outer {
name: String,
info: Inner,
}
#[derive(Deserialize)]
struct Inner {
count: i32,
foo: String,
}
let helper = Outer::deserialize(deserializer)?;
Ok(Object {
name: helper.name,
count: helper.info.count,
foo: helper.info.foo,
})
}
}
fn main() {
let j = r#"{
"name": "myobject",
"info": {
"count": 3,
"foo": "bar"
}
}"#;
println!("{:#?}", serde_json::from_str::<Object>(j).unwrap());
}
输出结果为:
Object {
name: "myobject",
count: 3,
foo: "bar"
}
有三个实质上不同的地方出现无关紧要的嵌套:
这三种都需要不同的方法。在这个问题中观察到#1。
要解决#2或#3,请参阅Is there a way to omit wrapper/root objects when deserializing objects with Serde?
答案 1 :(得分:-1)
现在您可以#[serde(flatten)]
如下:
#[derive(Serialize, Deserialize)]
struct Pagination {
limit: u64,
offset: u64,
total: u64,
}
#[derive(Serialize, Deserialize)]
struct Users {
users: Vec<User>,
#[serde(flatten)]
pagination: Pagination,
}