How to serialize and deserialize between two crates?

I have two crates, crate1 and crate2.

In crate1 I have the following type:

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "MyType", content = "value")]
pub enum MyType {
    TargetType(usize, usize),
}

and I get the serialized object:

let crate1_str = serde_json::to_string(&MyType::TargetType(1, 1))?;
"{\"MyType\":\"TargetType\",\"value\":[1,1]}"

In crate2 I have a type named MyType too, which is similar to the MyType in crate1:

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "MyType", content = "value")]
pub enum MyType {
    TargetType(TargetTypeWrapper),
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "TargetTypeWrapper", content = "value")]
pub enum TargetTypeWrapper {
    TargetType(usize, usize),
}

The difference between the two MyTypes is that the MyType from crate2 has more layer named TargetTypeWrapper which wrapper the struct TargetType.

let my_type = MyType2::TargetType(TargetTypeWrapper::TargetType(1, 1));
let crate2_str = serde_json::to_string(&my_type)?;
"{\"MyType\":\"TargetType\",\"value\":{\"TargetTypeWrapper\":\"TargetType\",\"value\":[1,1]}}"

For now I have got the object crate1_str in crate2, and I am trying to deserialize it into my_type (which is: let my_type = MyType2::TargetType(TargetTypeWrapper::TargetType(1, 1))). How can I implement the Deserialize trait to get it?

#[serde(untagged)]?

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.