You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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?
Thanks!
The text was updated successfully, but these errors were encountered:
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!
The text was updated successfully, but these errors were encountered: