简体   繁体   中英

Custom Map unmarshalling with JAXB

I have an XML which contains maps serialised like this:

<system>
  ...
  <entities>
    <entity>
      <string>key<string>
      <string><![CDATA[["a", "b", "c"]]]></string>
    </entity>
    ...
  </entities>
</system>

What I would like to get from this is that the <entities> are deserialised as Map<String, Object> with map.get(key) returning a List of strings.

class System {
  ...
  private Map<String, Object> properties;
}

So the question is how do I make it work with JAXB?

You have to use an XmlAdapter and the @XmlJavaTypeAdapter annotation.

Step 1 : Create a class Entity that represents your <entity> element and map it with JAXB.

Step 2 : Create a class that extends XmlAdapter<List<Entity>,Map<String,Object> and define the abstracts methods marshall and unmarshall.

Step 3 : Create a class Entities like this :

@XmlRootElement
@XmlSeeAlso({Entity.class})
@XmlAccessorType(XmlAccessType.FIELD)
public class Entities{

    @XmlElement(name="entity")
    @XmlJavaTypeAdapter(YourAdapter.class)
    private Map<String,Object> yourMap;

    //getters, setters, and methods
}

Then when you unmarshall your file, you'll have an Entities object that contains your map.

Please tell me if you're encountering trouble, of if this solution does fits your needs, so i can edit/append my answer.

EDIT :

If your Entities element is not your root element, then you can map it like this :

class ParentElement{

    //Other fields

    @XmlElement(name="entities")
    private Entities entities;

    //Getters, Setters, Methods
}

And keep the entities class

@XmlSeeAlso({Entity.class})
public class Entities{

    @XmlElement(name="entity")
    @XmlJavaTypeAdapter(YourAdapter.class)
    private Map<String,Object> yourMap;

    //getters, setters, and methods
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM