pdvrieze/xmlutil

Simpler customization for Map key names

JordanLongstaff opened this issue · 1 comments

Here's my XML data format (for simplicity, I've redacted a bunch of elements and attributes that are not essential to this issue):

<vessel_data version="2.6">
  <hullRace ID="0">
    // ...
  </hullRace>
  // More `hullRace`s with different `ID`s

  <vessel    uniqueID="0">
    // ...
  </vessel>
  // More `vessel`s with different `uniqueID`s
</vessel_data>

And here's the class representation I want to serialize it:

@Serializable
data class VesselData(
    val hullRaces: Map<Int, HullRace>,
    val vessels: Map<Int, Vessel>,
)

The default serialization policy uses key as the default key name for maps. The current workarounds are to either decode the elements into lists and then manually convert them into maps, but this means they're stored redundantly; or, override the deserialization policy. I'd like an easier way to specify the name of the attribute that defines the keys.

One idea would be to use the @XmlId annotation; both the HullRace and Vessel classes have their respective ID properties annotated with it. Alternatively, the key name could be defined by annotating the Map property, e.g.:

@Serializable
data class VesselData(
    @XmlMapKey("ID")
    val hullRaces: Map<Int, HullRace>,
    @XmlMapKey("uniqueID")
    val vessels: Map<Int, Vessel>,
)

An annotation to define the names of value attributes would also be helpful.

Seems like a reasonable addition to the default policy. I will add it to the list of features to add.