I am new to Rust and I am trying to deserialize JSON data using serde library. I have following JSON structure:
{
“foo”: “bar”,
“speech”: “something”
}
or
{
“foo”: “bar”,
“speech”: [“something”, “something else”]
}
or
{
“foo”: “bar”,
}
I.e. speech is optional and it can be either string or array of strings.
I can handle deserializing string/array of string using following approach:
#[derive(Debug, Serialize, Deserialize)]
struct foo {
pub foo: String,
#[serde(deserialize_with = "deserialize_message_speech")]
speech: Vec<String>
}
I can also handle deserializing optional string/string array attribute using approach:
#[derive(Debug, Serialize, Deserialize)]
struct foo {
pub foo: String,
#[serde(skip_serializing_if = "Option::is_none")]
speech: Option<Vec<String>>
}
or
struct foo {
pub foo: String,
#[serde(skip_serializing_if = "Option::is_none")]
speech: Option<String>
}
But combining it all together simply does not work. It seems deserialize_with does not work properly with Option type. Can somebody advice most straightforward and trivial way how to implement this (serde can be pretty complex, I have seen some crazy stuff :) )?