quick-xml icon indicating copy to clipboard operation
quick-xml copied to clipboard

Create attribute without using @ for compatibility with json serialization

Open jdmichaud opened this issue 1 year ago • 5 comments

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?

jdmichaud avatar Mar 29 '23 19:03 jdmichaud

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.

Mingun avatar Mar 29 '23 20:03 Mingun

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?

jdmichaud avatar Apr 15 '23 11:04 jdmichaud

No, intermediate serializer should be used with other format serializers. The quick-xml Serializer should be used directly

Mingun avatar Apr 15 '23 16:04 Mingun

@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?

Nickersoft avatar Feb 12 '24 12:02 Nickersoft

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

Mingun avatar Feb 12 '24 15:02 Mingun