Here is a Rust playground link with what I have so far.
I am working on a Rust project where the serialization/deserialization MUST be interoperable with a C# project. I have these two structs that are approximations of my C# classes to outline my case:
#[derive(Serialize, Deserialize, Debug)]
struct MyStruct<'a> {
#[serde(flatten)]
#[serde(borrow)]
otherStructMap: HashMap<&'a str, MyOtherStruct<'a>>
}
#[derive(Serialize, Deserialize, Debug)]
struct MyOtherStruct<'a> {
#[serde(flatten)]
#[serde(borrow)]
data: HashMap<&'a str, &'a str>
}
I have been using serde(flatten)
because it gets very close to what I want, but it is not correct. My Rust playground result takes these instances of my structs:
let mut map = HashMap::new();
map.insert("key1", "value1");
map.insert("key2", "value2");
let other = MyOtherStruct { data: map };
let mut map2 = HashMap::new();
map2.insert("key1", other);
let myStruct = MyStruct { otherStructMap: map2 };
And serializes it this way:
{
"key1": {
"key2": "value2",
"key1": "value1"
}
}
But this is not how C# wants this. It wants the field names kept, so deserialized like this:
{
"otherStructMap": {
"data": {
"key1": {
"key2": "value2",
"key1": "value1"
}
}
}
}
An important part of my needs is I have multiple generic HashMap<&str, _>
nested in my classes that need to be deserialized/serialized. I am new to Rust so I have tried all kinds of things like serialize_with
and deserialize_with
functions but I can’t get these right for a generic HashMap like I am using. It looks like I might be able to use a MapSerializer
and serialize_entry
each of the key-value pairs but, same as before, I can’t get this working.
Thanks a lot for the help
I tried to use serialize_with
or MapSerializer
to create a HashMap<&str, _>
approach and it works but it produces the exact same results as flatten: Rust Playground. I suspect this is close to a working solution if I knew how to make sure what I serialize_map is wrapped in another json node.
Jonathan Saraco is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.