serde-rs / json

Strongly typed JSON library for Rust
Apache License 2.0
4.88k stars 557 forks source link

String catch all #1029

Closed eliasposen closed 5 months ago

eliasposen commented 1 year ago

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!

tbu- commented 1 year ago

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.