从 Serde 1.0.34 开始,您现在可以使用#[serde(flatten)]
:
#[derive(Debug, Serialize, Deserialize)]
struct Test {
pub i: i64,
#[serde(flatten)]
pub team_size: TeamSize,
}
在此之前,最简单的解决方法是反序列化为私有助手类型并根据需要对其进行重组:
#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate serde_json;
use serde::{Serialize, Serializer, Deserialize, Deserializer};
#[derive(Debug)]
pub struct TeamSize {
pub min: i64,
pub max: i64,
}
#[derive(Debug)]
pub struct Test {
pub i: i64,
pub team_size: TeamSize,
}
// Private helper
#[derive(Serialize, Deserialize)]
struct Helper {
pub i: i64,
pub min: i64,
pub max: i64,
}
impl Serialize for Test {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer
{
let helper = Helper {
i: self.i,
min: self.team_size.min,
max: self.team_size.max,
};
helper.serialize(serializer)
}
}
impl<'de> Deserialize<'de> for Test {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>
{
let helper = Helper::deserialize(deserializer)?;
Ok(Test {
i: helper.i,
team_size: TeamSize {
min: helper.min,
max: helper.max,
},
})
}
}
fn main() {
let j = r#" { "i": -2, "min": 2, "max": 5 } "#;
let de: Test = serde_json::from_str(j).unwrap();
println!("{:#?}", de);
let ser = serde_json::to_string_pretty(&de).unwrap();
println!("{}", ser);
}