1

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

下面的 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() {   
}

}

4

1 回答 1

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());
于 2012-09-13T08:24:16.183 回答