如何部分反序列化 JSON 对象?

How to partially deserialise a JSON object?

我有一个 JSON 对象:

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

将其反序列化为自定义类型已经可以正常工作,使用:

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

我想要的是 {"foo":1,"bar":2} 作为 &[u8] 切片,以便我可以检查签名。

(我知道有关规范 JSON 表示的问题,并且已采取缓解措施。)

目前我正在浪费重新序列化 Content 对象(在 SignedContent 对象内)到一个字符串中并从中获取八位字节。

有没有更高效的方法?

看起来像是 serde_json::value::RawValue 的工作(可通过“raw_value”功能获得)。

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.

用法为:

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

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

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

然后您可以使用 content.get() 获取原始 &str