Serialize a `struct` field with another format with using `serde`

I have the following struct MyStruct, which implements Serialize:

#[derive(Serialize)]
struct MyStruct {
    fill: Fill
}

#[derive(Serialize)]
struct Fill {
    color: String
}

The serialized output format is:

let my_struct = MyStruct { fill: Fill { color: "White".into() } };
println!("{}", serde_json::to_string(&my_struct).unwrap())
//output
//{"fill":{"color":"White"}}

If I write the struct MyStruct above in this way:

#[derive(Serialize)]
struct MyStruct {
    //#[some serialize macro]
    fill_color: String
}

How can I make the serialized output format the same as before.
There is the field format function link on serde, I can't find a method to do it.

You can #[serde(rename)] the fill_color field to fill, and then use #[serde(serialize_with = "...")] and specify a function that serializes a string as a 1-key map.

3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.