Closed arik-so closed 2 months ago
I have an outer type ContainerType whose inner key bar can be either a string or a string array:
ContainerType
bar
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?
Update: it seems that adding #[serde(untagged)] fixes it:
#[serde(untagged)]
#[derive(Clone, Debug, Deserialize, Serialize)] #[serde(untagged)] pub enum StringOrStringArray { String(String), StringArray(Vec<String>), }
I have an outer type
ContainerType
whose inner keybar
can be either a string or a string array:When deserializing JSON whose
bar
value is a string, it works perfectly fine. However, when the JSON'sbar
field is an array, I get the following error:On the other hand, when I try to deserialize that value directly by substituting the container type definition:
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?