我正在编写一个websocket服务器,该服务器将传入的帧反序列化为serde_json::Value
,然后将此值传递给(可能有很多)回调。我希望回调将serde_json::Value
转换为新类型(例如下面示例中的MyType
),而无需进行编码/解码。在我看来,SERDE机械应该具有足够的信息来执行此操作(如果所包含的字段和类型不匹配,则可能会出错)。在下面的示例中,函数to_my_type()
代表此回调函数。是我要从此功能绕过的编码/解码。
我当然可以将原始编码数据传递给每个回调,但是每个回调将不得不分别进行解码。我想保留带有serde_json::Value
类型参数的回调的函数签名,以便不同的回调可以获取不同的类型,但是我可以使用通用的函数签名来注册它们。
#![feature(proc_macro)]
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
#[derive(Serialize, Deserialize)]
struct MyType {
a: bool,
}
fn as_json(a: &MyType) -> serde_json::Value {
let buf = serde_json::to_vec(a).unwrap();
serde_json::from_slice::<serde_json::Value>(&buf).unwrap()
}
fn to_my_type(value: serde_json::Value) -> MyType {
// How to convert a serde_json::Value into MyType without encode/decode pass?
let buf = serde_json::to_vec(&value).unwrap();
serde_json::from_slice::<MyType>(&buf).unwrap()
}
fn main() {
let store = MyType{a: true};
let raw_json = as_json(&store);
let _store2 = to_my_type(raw_json);
}
最佳答案
您可以使用 serde_json::from_value
函数将Value
转换为实现Deserialize
的任何类型:
fn to_my_type(value: serde_json::Value) -> MyType {
serde_json::from_value(value).unwrap()
}