Hello! I am working on a project where an api response contains metadata that is pretty inconsistent. I would like to retain this metadata in my struct as a string when doing serde_json::from_str() am often getting Error("invalid type: map, expected a string", ...) given the metadata is sometimes a json itself. E.g.
#[derive(Debug, Deserialize)]
struct MyStruct {
name: String,
metadata: String, // this is sometimes a string but may be any valid json
}
fn main() {
let json = r#"{
"name": "foobar",
"metadata": {"foo": "bar", "fizz": 42}
}"#;
let my_struct: MyStruct = serde_json::from_str(json).unwrap(); // Errors here
}
Is there a way to tell serde_json to just keep metadata as a string regardless if it is actually a map?
You can use Value or RawValue from the serde_json crate to match any kind of value. You can match on Value and use its string if it's a string or serialize the Value again if it is not.
Hello! I am working on a project where an api response contains metadata that is pretty inconsistent. I would like to retain this metadata in my struct as a string when doing
serde_json::from_str()
am often gettingError("invalid type: map, expected a string", ...)
given the metadata is sometimes a json itself. E.g.Is there a way to tell
serde_json
to just keepmetadata
as a string regardless if it is actually a map?Thanks!