I have two modules crate_old
and 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();
}
In each of the modules, there is a type MyStruct
. In the old crate, it is a struct
, and in the new one it is a enum
which has an viriant RealStruct
, which has the same struct as the MyStruct
in crate_old.
I get a serialized object in the 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}"
In crate_new, I have the following object:
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}"
How can I deserialize crate1_box_str
to an object the same as crate2_box
in crate_new? I thought it may need custom deserialize typetag
, but I can't find how. to do it.