jamesmunns / postcard

A no_std + serde compatible message library for Rust
Apache License 2.0
943 stars 91 forks source link

Can serialize `serde_json::Value`, but can't deserialize it #77

Open jeromegn opened 2 years ago

jeromegn commented 2 years ago

I'm getting a WontImplement error.

I suppose I'm surprised I'm able to serialize a value I can't ever deserialize and I'm wondering if I'm doing something wrong!

I'm not entirely sure which of the WontImplement cases I'm hitting either.

I'm looking into storing as a String or Vec<u8> instead.

iFreilicht commented 2 years ago

Can you show the definition of your struct you're trying to deserialize to and the exact error you're getting? There's no way to help you if we don't know what you're doing.

jeromegn commented 2 years ago

Oh yes, my bad.

    #[test]
    fn postcard_test() -> Result<(), Box<dyn std::error::Error>> {
        #[derive(Debug, Serialize, Deserialize, Eq, PartialEq)]
        struct Json(serde_json::Value);

        let json = Json(serde_json::json!({"foo": "bar"}));

        let bytes = postcard::to_allocvec(&json)?;
        let json2 = postcard::from_bytes(&bytes)?;

        assert_eq!(json, json2);

        Ok(())
    }
jamesmunns commented 2 years ago

So, serde_json::Value uses some of the "the details of deserialization are in the format" features of Serde.

This is fine for JSON, but non-self-describing binary formats like postcard can't generally do this for deserialization. This is mentioned in the docs.

You COULD have a wrapper type for each of the variants of serde_json::Value, but they are currently defined to encode "directly" on the wire, so no enum variant is present on the wire.

Unfortunately, I think getting "WontImplement" is correct in this case.