Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to partially deserialise a JSON object?

I have a JSON object:

{"content":{"foo":1,"bar":2},"signature":"3f5ab1..."}

Deserialising this into a custom type already works fine, using:

let s: SignedContent = serde_json::from_str(string)?;

What I want is {"foo":1,"bar":2} as a &[u8] slice, so that I can check the signature.

(I am aware of the issues around canonical JSON representations, and have mitigations in place.)

Currently I am wastefully re-serialising the Content object (within the SignedContent object) into a string and getting the octets from that.

Is there a more efficient way?

like image 680
fadedbee Avatar asked Oct 04 '20 07:10

fadedbee


People also ask

How do I deserialize an object in JSON?

A common way to deserialize JSON is to first create a class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method.

What is the difference between serialize and deserialize JSON?

JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object). If you serialize this result it will generate a text with the structure and the record returned.

What does it mean to deserialize a JSON?

The process whereby a lower-level format (e.g. that has been transferred over a network, or stored in a data store) is translated into a readable object or other data structure. In JavaScript, for example, you can deserialize a JSON string to an object by calling the function JSON.

What is JsonExtensionData?

[JsonExtensionData] allows you to do is to serialize elements of a JSON document which does not have matching properties on the destination object to the dictionary which is decorated with the [JsonExtensionData] attribute.


1 Answers

Looks like a job for serde_json::value::RawValue (which is available with the "raw_value" feature).

Reference to a range of bytes encompassing a single valid JSON value in the input data.

A RawValue can be used to defer parsing parts of a payload until later, or to avoid parsing it at all in the case that part of the payload just needs to be transferred verbatim into a different output object.

When serializing, a value of this type will retain its original formatting and will not be minified or pretty-printed.

With usage being:

#[derive(Deserialize)]
struct SignedContent<'a> {

    #[serde(borrow)]
    content: &'a RawValue,

    // or without the 'a
    //content: Box<RawValue>
}

You can then use content.get() to get the raw &str.

like image 131
kmdreko Avatar answered Oct 16 '22 17:10

kmdreko