使用远程对象的代理类型串行化



如何使用Serde为远程类型创建序列化程序代理对象?这里有一个最小的例子(操场(:

use serde; // 1.0.104
use serde_json; // 1.0.48
struct Foo {
bar: u8,
}
impl Foo {
pub fn new() -> Self {
Foo { bar: 10 }
}
pub fn val(&self) -> u8 {
self.bar
}
}
#[derive(serde::Serialize)]
#[serde(remote = "Foo")]
struct Bar {
#[serde(getter = "Foo::val")]
val: u8,
}
fn main() {
let foo = Foo::new();
let res = serde_json::to_string(&foo).unwrap();
println!("{}", res);
}

它找不到实现:

error[E0277]: the trait bound `Foo: _IMPL_SERIALIZE_FOR_Bar::_serde::Serialize` is not satisfied
--> src/main.rs:27:37
|
27   |     let res = serde_json::to_string(&foo).unwrap();
|                                     ^^^^ the trait `_IMPL_SERIALIZE_FOR_Bar::_serde::Serialize` is not implemented for `Foo`
| 
::: /playground/.cargo/registry/src/github.com-1ecc6299db9ec823/serde_json-1.0.48/src/ser.rs:2233:8
|
2233 |     T: Serialize,
|        --------- required by this bound in `serde_json::ser::to_string`

#[serde(remote = "Foo")]不能破坏孤立规则,因此不能真正实现类型Foo的特征。

您必须将其与#[serde(with = "...")]一起使用。

一个简单的方法是创建一个用于序列化的小包装器:

#[derive(serde::Serialize)]
struct FooWrapper<'a>(#[serde(with = "Bar")] &'a Foo);

并将其用作CCD_ 4(永久链接到操场(。

这将使用远程定义Bar按预期序列化Foo

对于反序列化,您可以使用Bar::deserialize,并且您将直接获得Foo

另请参阅:

  • serde的文档:为不同机箱中的类型派生De/Serialize

最新更新