不同 crate 之间的序列化和反序列化

问题描述 投票:0回答:0

我有两个模块 crate_old 和 crate_new:

/*
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"
typetag = "*"
*/

pub mod crate_old {
    use serde::{Deserialize, Serialize};

    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct MyStruct(
        #[serde()]
        pub usize
    );

    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct MyStructAppend(
        pub usize,
        pub usize
    );

    #[typetag::serde(tag = "MyTrait", content = "value")]
    pub trait MyTrait {}

    #[typetag::serde]
    impl MyTrait for MyStruct {}

    #[typetag::serde(tag = "RealStruct", content = "value")]
    pub trait RealStruct {}

    #[typetag::serde]
    impl RealStruct for MyStruct {}

    #[typetag::serde]
    impl RealStruct for MyStructAppend {}
}

pub mod crate_new {
    use serde::{Deserialize, Serialize};

    #[derive(Debug, Clone, Serialize, Deserialize)]
    #[serde(untagged)]
    pub enum RealStruct {
        MyStruct(usize),
        MyStructAppend(usize, usize),
    }

    #[typetag::serde(tag = "MyTrait", content = "value")]
    pub trait MyTrait {}

    #[typetag::serde]
    impl MyTrait for RealStruct {}
}

fn main() {
    let crate1_box: Box<dyn crate_old::MyTrait> = Box::new(crate_old::MyStruct(10));
    let crate1_box_str = serde_json::to_string(&crate1_box).unwrap();
    assert_eq!(crate1_box_str, r#"{"MyTrait":"MyStruct","value":10}"#);

    let crate2_box: Box<dyn crate_new::MyTrait> = Box::new(crate_new::RealStruct::MyStruct(10));
    let crate2_box_str = serde_json::to_string(&crate2_box).unwrap();
}

在每个模块中,都有一个类型 MyStruct。在旧的 crate 中,它是一个结构体,而在新的 crate 中,它是一个具有变体 RealStruct 的枚举,它与 crate_old 中的 MyStruct 具有相同的结构。

我在 crate_old 中得到一个序列化对象:

let crate1_box: Box<dyn crate_old::MyTrait> = Box::new(crate_old::MyStruct(10));
let crate1_box_str = serde_json::to_string(&crate1_box)?;
"{\"MyTrait\":\"MyStruct\",\"value\":10}"

在 crate_new 中,我有以下对象:

let crate2_box: Box<dyn crate_new::MyTrait> = Box::new(crate_new::RealStruct::MyStruct(10));
let crate2_box_str = serde_json::to_string(&crate2_box)?;
"{\"MyTrait\":\"RealStruct\",\"value\":10}"

如何将 crate1_box_str 反序列化为与 crate_new 中的 crate2_box 相同的对象?我认为它可能需要自定义反序列化类型标签,但我找不到方法。去做。

rust traits serde
© www.soinside.com 2019 - 2024. All rights reserved.