Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unexpected JSON serialization result #64

Open
ede1998 opened this issue Dec 21, 2024 · 2 comments
Open

Unexpected JSON serialization result #64

ede1998 opened this issue Dec 21, 2024 · 2 comments

Comments

@ede1998
Copy link

ede1998 commented Dec 21, 2024

Thanks for this crate! It comes in very handy with my current ESP32 project.

Using picoserve::extract::Json yields an unexpected result when serializing a HashMap. Is this intentional? Can I get to the normal representation somehow?

Expected result:

'{"example":null}'

Actual result:

'[["example",null]]'

Minimal sample (I use hashbrown on the ESP, but std gives the same result):

// picoserve = { version = "0.13.2", features = ["std"] }
// serde = { version = "1.0.216", features = ["derive"] }
// serde_json = "1.0.134"
// tokio = { version = "1.42.0", features = ["macros", "rt"] }

use serde_json;
use picoserve::response::sse::EventData;
use std::collections::HashMap;


#[tokio::main(flavor = "current_thread")]
async fn main() {
  let data: HashMap<&str, ()> = [("example", ())].into();

  let x = serde_json::to_string(&data).unwrap();
  println!("Expected: '{}'", x);


  let j = picoserve::extract::Json(&data);
  let mut buffer = vec![0u8; 1000];
  let _ = j.write_to(&mut buffer.as_mut_slice()).await;
  println!("Actual: '{}'", std::str::from_utf8(&buffer).unwrap().trim_matches('\0'));
}
@sammhicks
Copy link
Owner

This is by "design", if by design you mean the simplest implementation, as I don't use map serialization myself.

I think I'll change to implementation to mirror what serde_json does, which is to have a specific serializer for map keys, which serializes strings and characters as string keys, converts numerical types to strings, and rejects all other types.

Interestingly, de-serializing to hashmaps hits an unreachable!() in serde_json_core which I use, so be warned.

@ede1998
Copy link
Author

ede1998 commented Dec 27, 2024

It's not a huge deal for me, just surprising.
Looking at the code, serde_json_core still seems to handle str keys properly at least:

https://github.com/rust-embedded-community/serde-json-core/blob/ca6745785c6d315d532170a33bff826377c693c9/src/de/map.rs#L162

But yeah, might get a panic if using an integer key. Luckily for me, I don't deserialize JSON in my project :D
Otherwise deserialize_with/as might be helpful I think.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants