Serialize struct with one field as inner field

I've got a struct with one field.
How i can serialize it as the inner field without the extra wrapper.

For example how i can make ExampleStruct serialize as Vec<u64>.

  • This: [1, 2, 3]
  • Not this { "vec": [1, 2, 3] }
use serde::Serialize;

#[derive(Debug, Serialize)]
struct ExampleStruct{
    vec: Vec<u64>
}

fn main() {
    let example = ExampleStruct { vec: vec![1,2,3] };
    println!("{:?}", serde_json::to_string(&example));
}

I think the easiest solution in your case would be to just make ExampleStruct a tuple struct instead of a struct with named fields.

use serde::Serialize;

#[derive(Debug, Serialize)]
struct ExampleStruct(Vec<u64>);

fn main() {
    let example = ExampleStruct(vec![1,2,3]);
    println!("{}", serde_json::to_string(&example).unwrap());
}

Playground.

Note that transparent treatment of newtype-style structs is just an implementation choice of serde_json; the field is still wrapped with serialize_newtype_struct, which merely encourages serializers to consider treating it fully transparently.

To hide the layer completely from serializers, it’s also possible to use #[serde(transparent)] instead. This is also compatible with named fields.

3 Likes

Ah yes, forgot about serde(transparent). I was looking into making serde(flatten) work on the inner field, but it doesn't work with collections. My other thought was serde(untagged), but that obviously only applies to enums.

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.