我有一个JSON对象,其中包含一些元数据键和一个大数据有效负载.我的服务关注用于记录和路由的元数据,但不关心有效负载,而是将有效负载传递给另一个服务.我永远不需要出于任何原因查看有效载荷.
现在,有效负载在我的结构中表示为serde_json::Value.通过剖析,我已经看到(de)序列化Value需要花费大量的时间.
在Serde中是否有一种机制可以捆绑有效负载而无需支付将其反序列化为组件值的成本,只是需要在以后重新序列化它们?
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
#[derive(Serialize, Deserialize)]
struct DataBlob<'a> {
id: &'a str,
priority: u8,
// payload: OpaqueValue,
}
fn main() {
let input = r#"{
"id": "cat",
"priority": 42,
"payload": [1, 2, 3, 4]
}"#;
let parsed = serde_json::from_str::<DataBlob>(input).expect("Could not deserialize");
let output = serde_json::to_string(&parsed).expect("Could not serialize");
assert!(output.contains("payload"));
}
Run Code Online (Sandbox Code Playgroud)
这是在 serde_json 1.0.29 中作为 type 添加的RawValue。它必须使用该raw_value功能启用,然后放置在参考后面:
extern crate serde; // 1.0.79
#[macro_use]
extern crate serde_derive; // 1.0.79
extern crate serde_json; // 1.0.30, features = ["raw_value"]
#[derive(Serialize, Deserialize)]
struct DataBlob<'a> {
id: &'a str,
priority: u8,
payload: &'a serde_json::value::RawValue,
}
fn main() {
let input = r#"{
"id": "cat",
"priority": 42,
"payload": [1, 2, 3, 4]
}"#;
let parsed = serde_json::from_str::<DataBlob>(input).expect("Could not deserialize");
let output = serde_json::to_string(&parsed).expect("Could not serialize");
assert!(output.contains("payload"));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
877 次 |
| 最近记录: |