Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enum deserialization not working #1129

Closed
arik-so opened this issue May 7, 2024 · 1 comment
Closed

Enum deserialization not working #1129

arik-so opened this issue May 7, 2024 · 1 comment

Comments

@arik-so
Copy link

arik-so commented May 7, 2024

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
Copy link
Author

arik-so commented May 7, 2024

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

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

@arik-so arik-so closed this as completed May 7, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

1 participant