dtolnay / typetag

Serde serializable and deserializable trait objects
Apache License 2.0
1.19k stars 38 forks source link

serialize and deserialize dyn trait #31

Closed gangliao closed 2 years ago

gangliao commented 3 years ago

Currently, I want to serialize and deserialize such a structure, but I can't succeed anyway.

@dtolnay Thank you.

            use serde::{
                de::{DeserializeOwned, Deserializer, Error, Visitor, MapAccess, SeqAccess},
                ser::{self, Serialize, Serializer},
            };
            use serde_json;

        trait Event {
            fn as_any(&self) -> &dyn Any;
        }

        struct C {
            other_struct: Arc<dyn Event>,
        }

        struct D {
            value: usize,
        }

        impl Event for C {
            fn as_any(&self) -> &dyn Any {
                self
            }
        }

       impl Event for D {
            fn as_any(&self) -> &dyn Any {
                self
            }
        }

        let x: &dyn Event = &C {
            other_struct: Arc::new(D { value: 10 }),
        };
       // let json = serde_json::to_string(&x)?;
       // let de: C = serde_json::from_str(&json)?;
dtolnay commented 2 years ago

Hi @gangliao, sorry that no one was able to provide guidance here. If this is still an issue, you could try taking this question to any of the resources shown in https://www.rust-lang.org/community.