简体   繁体   English

使用JAXB解组自定义地图

[英]Custom Map unmarshalling with JAXB

I have an XML which contains maps serialised like this: 我有一个XML,其中包含这样序列化的地图:

<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. 我想从中得到的是<entities>被反序列化为Map<String, Object> ,而map.get(key)返回字符串列表。

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

So the question is how do I make it work with JAXB? 所以问题是如何使它与JAXB一起使用?

You have to use an XmlAdapter and the @XmlJavaTypeAdapter annotation. 您必须使用XmlAdapter和@XmlJavaTypeAdapter批注。

Step 1 : Create a class Entity that represents your <entity> element and map it with JAXB. 步骤1:创建一个表示您的<entity>元素的类Entity,并将其与JAXB映射。

Step 2 : Create a class that extends XmlAdapter<List<Entity>,Map<String,Object> and define the abstracts methods marshall and unmarshall. 步骤2:创建一个扩展XmlAdapter<List<Entity>,Map<String,Object>并定义摘要方法marshall和unmarshall。

Step 3 : Create a class Entities like this : 第3步:创建一个这样的类实体:

@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. 然后,在解组文件时,将有一个包含地图的Entities对象。

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 : 如果您的Entities元素不是您的根元素,则可以这样映射它:

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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