ron-rs/ron

How to deserialize a struct?

Closed this issue · 1 comments

Hi guys. I am serializing a struct manually (because of something bigger I need to do) and the result of the serialization is this:

SerializeDyn(
    type: "engine_utils::types::registry::tests::Player",
)

Now I need to deserialize it back manually.. but I'm having some problems trying to understand how to do that.. Because for now I have this piece of code:

fn deserialize<'de>(deserializer: ron::Deserializer<'de, &mut Vec<u8>>)
{
    deserializer.deserialize_struct("SerializeDyn", &["type"], SerializeDynVisitor);
}

struct SerializeDynVisitor;
impl<'de> Visitor<'de> for SerializeDynVisitor {
    type Value = Box<dyn Any>;

    fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(formatter, "a serialize dyn struct")
    }
    
    //Apparently when I deserialize a struct, this is what ends up being called in the visitor
    fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
        where A: serde::de::MapAccess<'de>
    {
        let entry = map.next_entry::<&str, String>()?;    //Here I get the error!
        
        todo!()
    }
}

But when I do map.next_entry... I get this error:

Err(
    InvalidValueForType {
        expected: "a borrowed string",
        found: "the string \"type\"",
    },
)

What does this mean? I can't do map.next_entry::<String, String>()? because it panics saying: IdDeserializer may only be used for identifiers but I don't understand what I should do to read the value of the field.

Thanks for coming across this issue! This was indeed an issue on our end that serde-derived code never triggered. Whether one should be able to deserialise a field name into a String is another question - so far we still do not support that but we easily could in the future. However, your use case should now (once I've merged the PR) work on the main branch (see the new 423_de_borrowed_identifier.rs test).