Is it possible to skip field serialization using Serde?

I have two structures:

#[derive(Serialize)] struct Post { title: String, // ...more fields..., comments: Vec<Comment>, } #[derive(Serialize)] struct Comment { body: String, // ...more fields..., } 

I want to create 2 types of JSON files:

  • JSON a Vec<Post> index, which should include all fields except comments .
  • A JSON a Post that includes all fields.

Is it possible to achieve this with the Serialize getive attribute? I found the skip_serializing_if attribute in the Serde documentation, but as far as I can see, this is not useful for me because I want to skip not based on the value of the field, but based on which the JSON file is created.

Now I am creating an index using the json! macro json! which requires manually listing all the Post fields, but I hope there will be a better way to do this.

+7
rust serde
source share
1 answer

I want to generate 2 types of JSON files

I read that as "2 types of JSON files", so I refer to this as a solution. I would create cover types that are customizable for each context. They can refer to the original type to avoid too much memory overhead:

 #[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"}]} } 

playground


In an editorial, I found that this type of multi-type structure is very useful when writing web applications in Ruby using a roaring stone . These new types allow behavioral hangouts specific to specific contexts, such as validation or persistence.

+4
source share

All Articles