serde-rs / json

Strongly typed JSON library for Rust
Apache License 2.0
4.7k stars 536 forks source link

Enum deserialization not working #1129

Closed arik-so closed 2 months ago

arik-so commented 2 months ago

I have an outer type ContainerType whose inner key bar can be either a string or a string array:

use serde::{Deserialize, Serialize};

#[derive(Clone, Debug, Deserialize, Serialize)]
pub enum StringOrStringArray {
    String(String),
    StringArray(Vec<String>),
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct ContainerType {
    foo: u64,
    bar: StringOrStringArray
}

When deserializing JSON whose bar value is a string, it works perfectly fine. However, when the JSON's bar field is an array, I get the following error:

Json(Error("invalid type: sequence, expected string or map", line: 0, column: 0))

On the other hand, when I try to deserialize that value directly by substituting the container type definition:

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct ContainerType {
    foo: u64,
    bar: Vec<String>
}

There seems to be an issue that might be tangentially related to this, but I'm not sure if it actually is. Is there something I'm doing incorrectly?

arik-so commented 2 months ago

Update: it seems that adding #[serde(untagged)] fixes it:

#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum StringOrStringArray {
    String(String),
    StringArray(Vec<String>),
}