quick-xml
quick-xml copied to clipboard
Create attribute without using @ for compatibility with json serialization
I have a data structure with an attribute:
#[derive(Debug, Serialize, Deserialize)]
pub struct Foo {
#[serde(rename = "@bar")]
pub bar: String,
}
Which (de)serializes to:
<foo bar="blabla"/>
For this to work I had to add @
. However, I need to (de)serialize in XML and json. So now, in json, the field appear as @bar
:
{
"foo": {
"@bar": "blabla",
},
}
And that's a problem for me. Is there a way to mark a field as attribute without modifying its name?
Is there a way to mark a field as attribute without modifying its name?
Unfortunately, no.
You still can solve this problem partially. You can use #[serde(alias = "...")]
to allow deserialization both from XML and JSON (but in XML the field will be deserialized either from element or attribute). For the serialization you could write intermediate serializer, which will strip @
from serialized fields and forward them to the underlying serializer. I think, I even accept a PR that will add such a serializer to quick-xml.
For the serialization you could write intermediate serializer, which will strip @ from serialized fields and forward them to the underlying serializer. I think, I even accept a PR that will add such a serializer to quick-xml.
But if I were to do that, wouldn't the underlying XML serializer serialize the field as an element?
No, intermediate serializer should be used with other format serializers. The quick-xml Serializer
should be used directly
@Mingun I'm running up against this issue myself right now, and have been scouring the serde docs trying to find an approach I could use. I'm only interested in serialization, and modifying how data is serialized based on whether it's XML or JSON.
Could you share any examples of the intermediate serialization approach you mentioned?
You can look at the Readable
and Compact
imlementations in serde_test
here:
https://github.com/serde-rs/test/blob/1bedc0c7830c3207802b4b0614977c71608461cd/src/configure.rs#L181