如何通过JAXB Annotation Class序列化此JSON格式?

时间:2012-09-12 22:13:52

标签: java xml json jaxb

我正在寻找JAXB注释类,它可以序列化为以下json格式。 JSON格式:{"name":"xyz","attr1":"attr1value","attr2":"attr2value",.....}} 在上面的JSON格式中,name是必需属性, 其他人不是,但用户应该能够传递属性。

下面的JaxB注释类,可以序列化为JSON格式 {"name":"xyz","openContentMap":{"attr1":"attr1value","attr2":"attr2value", so on}}。 但我们想要JaxB注释,可以序列化这种格式{"name":"xyz","attr1":"attr1value","attr2":"attr2value",.....}}

@XmlRootElement
public class MyJaxbBean  {

private String name;
private Map<String, String> openContentMap = new HashMap<String, String>();

@XmlAnyElement
public Map<String, String> getOpenContentMap() {
    return openContentMap;
}

@XmlAnyElement
public void setOpenContentMap(String key, String value) {
    openContentMap.put(key, value);
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public MyJaxbBean() {   
}

}

1 个答案:

答案 0 :(得分:3)

使用org.codehaus.jackson.annotate.JsonAnyGetterorg.codehaus.jackson.annotate.JsonAnySetter

@XmlRootElement
public class MyJaxbBean
{
   private String name;

   private Map<String, String> openContentMap = new HashMap<String, String>();

   public String getName()
   {
      return name;
   }

   public void setName(String name)
   {
      this.name = name;
   }

   @JsonAnyGetter
   public Map<String, String> getOpenContentMap()
   {
      return openContentMap;
   }

   @JsonAnySetter
   public void add(final String key, final String value)
   {
      openContentMap.put(key, value);
   }
}  

运作良好

  String json = "{\"name\":\"xyz\",\"attr1\":\"attr1value\",\"attr2\":\"attr2value\"}";
  MyJaxbBean agr = new ObjectMapper().readValue(json, MyJaxbBean.class);
  System.out.println(agr.getName() + " " + agr.getOpenContentMap());