Serde 使用远程对象的代理类型序列化

Serde serialize with proxy type for remote object

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

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);

并将其用作 serde_json::to_string(&FooWrapper(&foo)) (permalink to the playground).

这将使用远程定义 Bar.

按照您的预期序列化 Foo

反序列化可以使用Bar::deserialize,直接得到一个Foo

另请参阅: