samscott89 / serde_qs

Serde support for querystring-style strings
Apache License 2.0
193 stars 67 forks source link

`serde_json::Value`: cannot deserialize primitive at the top level.Try deserializing into a struct. #77

Open Altair-Bueno opened 1 year ago

Altair-Bueno commented 1 year ago

Summary

Cannot deserialize query string into dynamic objects such as serde_json::Value or toml::Value

Current behaviour

Deserialization fails. Serialization succeeds

Expected behaviour

Serialization and deserialization shouldn't fail on dynamic objects.

Minimal example

// main.rs
fn main() -> Result<(), serde_qs::Error> {
    let payload = "hello=10";
    let json_value: serde_json::Value = serde_qs::from_str(payload)?;
    let expected = serde_json::json!({ "hello": 10 });
    assert_eq!(json_value, expected);
    Ok(())
}
# Cargo.toml
[package]
name = "primitive-top-level"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
serde_json = "1.0.91"
serde_qs = "0.11.0"
Error: Custom("cannot deserialize primitive at the top level.Try deserializing into a struct.")
chmielot commented 11 months ago

Try deserializing into <HashMap<String, serde_json::Value>> Edit: I ran into the same issue and I need the top level structure to be a serde_json::Value to be able to dynamically traverse the object tree by a given key. My actual workaround is:

serde_json::to_value(
        serde_qs::Config::new(5, false)
            .deserialize_bytes::<HashMap<String, serde_json::Value>>(&bytes)?,