Converting from one struct to another using Serde

Converting from one struct to another using Serde


I've built a FFI connector to some lib that provides Vector and HashMap like data structures. Those structures hold basic types like i64, f64 and String. But also more complex ones, that I wrap in structs. I use Serde for easy conversion between Rust types and those provided by the FFI. Basically, that FFI for me is the serialized version of my data.

This works perfectly well for the basic types. With the complex ones, wrapped in structs, I don't seem to find a solution. That is mostly due to my missing understanding of how to build structures, like structs in Serde, that require one to collect all detail information upfront and only in the end construct the output.

Test Case

To better understand what happens behinde the scenes with Serde, I've created a very basic test case, with a struct A {field_A: String, field_B: String} that shall be serialized into a struct B {field_A: String, field_B: String}.

Example on Rust Playground


The whole Serde approach is very generic and I don't seem to understand how one needs to utilize it for structs. My understanding right now is, that I get the struct as a map with key/value pairs that I have to work on in the serialize_field and end functions of my ser::SerializeStruct trait implementation. As the implementation is very generic, I don't know at that point, what data I get (value: &T) so I struggle to handle it (see compilation errors in line 255f in my playground example).

In the end I'm convinced that I lack a better understanding on Serdes approach. Would be great if you could help me or guide me to a tutorial that goes beyond writing to streams.

Are you looking for something like the serde-transcode crate?

It provides its own serializers and deserializers that have been wired up to convert directly without needing an intermediate representation (e.g. JSON).

serde-transcode is the opposite thing than is wanted here — it hooks up a Deserializer input to a Serializer output, converting one serialization format to another without any intermediate Rust types.

(I don't know of an existing library that does the other thing. I suspect that doing so is a much harder problem.)

1 Like

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.