stacker225
stacker225

Reputation: 35

Why do I get duplicate tags when serializing an enum with serde?

I have this code:

let vid = VideoLayer::VideoConcatLayer(VideoConcatLayer {
    list: vec![VideoLayer::VideoAssetLayer(VideoAssetLayer {
        asset: T3Val::Ready(
            Ready {
                val: "hello".to_string()
            })
        })]
    });

Basically VideoLayer and T3Val are enums and VideoConcatLayer, VideoAssetLayer, and Ready are structs. The problem is that when I try to serialize it with serde, the "type" field is duplicated and it throws an error.

The serialized result is here:

{"type":"VideoConcatLayer","type":"VideoConcatLayer","list":[{"type":"VideoAssetLayer","type":"VideoAssetLayer","asset":{"type":"Ready","type":"Ready","val":"hello"}}]}

Upvotes: 1

Views: 228

Answers (1)

Caesar
Caesar

Reputation: 8544

Since you won't share the code to reproduce the problem, I had to guess:

use serde::Serialize;

#[derive(Serialize)]
#[serde(tag = "type")]
enum VideoLayer {
    VideoConcatLayer(VideoConcatLayer),
}

#[derive(Serialize)]
#[serde(tag = "type")]
struct VideoConcatLayer {
    list: Vec<…>,
}

Delete the #[serde(tag = "type")] from the structs, only put it onto enums, and your problem will go away.

And for future questions, please always share the full code necessary to reproduce your problem, maybe with a playground link or including a list of dependencies.

Upvotes: 2

Related Questions