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?
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.
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.
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.
[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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With