将对象集合序列化为JSON和XML

时间:2014-07-21 13:00:01

标签: java xml json web-services jaxb

我有一个简单的Web服务,它以XML和JSON格式使用和生成一些bean。然后我有一个包含对象集合的bean:

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Company {

  @XmlElementWrapper(name = "addresses")
  @XmlElement(name = "address")
  private Collection<Address> addresses;
  ...
}

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Address{
  private String street;
  private String city;
  private String country;
  ...
}

序列化后我有这个XML:

<company>
 <addresses>
   <address>
      <street>Testowa 1A</street>
      <city>Warszawa</city>
      <country>Polska</country>
   </address>
   <address>
      <street>Testowa 2A</street>
      <city>Warszawa</city>
      <country>Polska</country>
   </address>
 </addresses>
</company>

这是正确的和JSON:

"company" : {
  "addresses": {
     "address": [ {"street": "Testowa 1A", "city": "Warszawa", "country": "Polska"} ],
     "address": [ {"street": "Testowa 2A", "city": "Warszawa", "country": "Polska"} ]
  }
}

问题在于JSON。我的Web服务用户无法接受序列化集合的表示法。他们需要这样的东西:

"company" : {
  "addresses": [
     {"street": "Testowa 1A", "city": "Warszawa", "country": "Polska"},
     {"street": "Testowa 2A", "city": "Warszawa", "country": "Polska"}
  ]
}

如果我删除@XmlElementWrapper我将拥有我需要的JSON,但我的XML将不正确(没有&#39;地址&#39;标记):

<company>
  <address>
     <street>Testowa 1A</street>
     <city>Warszawa</city>
     <country>Polska</country>
  </address>
  <address>
    <street>Testowa 2A</street>
     <city>Warszawa</city>
     <country>Polska</country>
  </address>
</company>

知道如何满足这两个要求吗?

1 个答案:

答案 0 :(得分:1)

JAXB (JSR-222)本身并不涵盖如何将对象转换为JSON或从JSON转换对象。这意味着答案将取决于您正在使用的当前正在解释JAXB注释的JSON绑定实现。

EclipseLink JAXB (MOXy)中,我们为JSON绑定提供了一个名为JSON_WRAPPER_AS_ARRAY_NAME的运行时属性,用于启用您要查找的行为。