我有两个结构:
#[derive(Serialize)]
struct Post {
title: String,
// ...more fields...,
comments: Vec<Comment>,
}
#[derive(Serialize)]
struct Comment {
body: String,
// ...more fields...,
}
Run Code Online (Sandbox Code Playgroud)
我想生成两种JSON文件:
Vec<Post>其中应包括除了之外的所有字段comments.Post包含所有字段的JSON .是否可以使用Serializederive属性实现此目的?我skip_serializing_if在Serde的文档中找到了属性,但据我所知,它对我没用,因为我想跳过不基于字段的值但是基于我生成的JSON文件.
现在我正在使用json!宏生成索引,需要手动列出所有字段,Post但我希望有更好的方法来做到这一点.
我想生成2种JSON文件
我将其理解为“2种类型的 JSON 文件”,因此我将其作为解决方案。我会创建适合每个上下文的包装类型。这些可以引用原始类型以避免过多的内存开销:
#[derive(Serialize)]
struct LightweightPost<'a> {
title: &'a String,
}
impl<'a> From<&'a Post> for LightweightPost<'a> {
fn from(other: &'a Post) -> Self {
LightweightPost {
title: &other.title,
}
}
}
fn main() {
let posts = vec![
Post {
title: "title".into(),
comments: vec![Comment { body: "comment".into() }],
},
];
let listing: Vec<_> = posts.iter().map(LightweightPost::from).collect();
println!("{}", serde_json::to_string(&listing).unwrap());
// [{"title":"title"}]
println!("{}", serde_json::to_string(&posts[0]).unwrap());
// {"title":"title","comments":[{"body":"comment"}]}
}
Run Code Online (Sandbox Code Playgroud)
在编辑方面,我发现这种类型的多类型结构在使用roar gem在 Ruby 中编写 Web 应用程序时非常有用。这些新类型允许在某些地方挂起特定于某些上下文的行为,例如验证或持久性。