Im using serde with serde-xml-rs to deserialize a xml document to a rust struct. It works well but I am trying to tidy up some.
A part of my xml looks like:
<TextColor>
<R>255</R>
<G>255</G>
<B>255</B>
</TextColor>
which I can deseriealize using
#[derive(Deserialize, Debug)]
#[serde(deny_unknown_fields)]
pub struct TextColor {
#[serde(rename="R")]
r: u64,
#[serde(rename="G")]
g: u64,
#[serde(rename="B")]
b: u64,
}
However, I found the rename_all attrib and it seemed to fit my bill here:
#[derive(Deserialize, Debug)]
#[serde(deny_unknown_fields, rename_all = "snake_case")]
pub struct TextColor {
r: u64,
g: u64,
b: u64,
}
But this now gives this error:
thread 'main' panicked at 'calledResult::unwrap()on anErrvalue: unknown fieldR, expected one ofr,g,b', src/libcore/result.rs:1009:5
Am I right in assuming rename_all only works when serializing data, and not deserializing?
Is there some way of automatically mapping the xml file's CamelCased names to snake_case names without specifying a rename attr on each field?
You're doing it completely correctly. serde-xml is reading the wrong table when looking at field names.
Thanks for quick response! Do you want me to bring up this issue over in serde-xml camp too, or are you coordinating it?
@martinlindhe the equivalent of the rename attributes you showed would be rename_all = "UPPERCASE". Typically rename_all = "snake_case" would be used on enums only.
#[derive(Deserialize)]
#[serde(rename_all = "snake_case")]
enum Status {
QualifiedSuccess, // renamed to look for "qualified_success" in the input
AbjectFailure, // renamed to look for "abject_failure" in the input
}
@dtolnay Alright! It seems to work correctly for me now, using PascalCase and a few rename="..." because the XML i'm working with is rather inconsistent. Thank you so much for your help.
in case someone is here for deserializing camelCase response into rust structs, here it is
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Card {
pub short_url: String,
pub short_link: String,
pub date_last_activity: DateTime<Utc>,
pub attachments: Vec<Attachment>
}
Most helpful comment
in case someone is here for deserializing camelCase response into rust structs, here it is