I'm using Serde to deserialize an XML file which has the hex value 0x400
as a string and I need to convert it to the value 1024
as a u32
.
Do I need to implement the Visitor
trait so that I separate 0x and then decode 400 from base 16 to base 10? If so, how do I do that so that deserialization for base 10 integers remains intact?
The
deserialize_with
attributeThe easiest solution is to use the Serde field attribute
deserialize_with
to set a custom serialization function for your field. You then can get the raw string and convert it as appropriate:playground
Note how this can use any other existing Serde implementation to decode. Here, we decode to a string slice (
let s: &str = Deserialize::deserialize(deserializer)?
). You can also create intermediate structs that map directly to your raw data, deriveDeserialize
on them, then deserialize to them inside your implementation ofDeserialize
.Implement
serde::Deserialize
From here, it's a tiny step to promoting it to your own type to allow reusing it:
playground
This method allows you to also add or remove fields as the "inner" deserialized type can do basically whatever it wants.
See also: