Spring Boot(Jackson):如何避免将类名序序化为JSON

时间:2016-05-12 10:08:51

标签: json rest spring-boot jackson

我正在使用从REST应用程序公开的一些XML,并希望在我自己的REST服务中将其公开为JSON。

现在我有以下POJO:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "salesMarket"
})
@XmlRootElement(name = "salesMarkets")
public class SalesMarkets {

protected List<SalesMarket> salesMarket;

public List<SalesMarket> getSalesMarket() {
    if (salesMarket == null) {
        salesMarket = new ArrayList<SalesMarket>();
    }
    return this.salesMarket;
   }

}

产生以下JSON:

  "salesMarkets": {
"salesMarket": [
  {
    "brands": {
      "brand": [
        "DAN"
      ]
    },
    "code": "999"
  },
  {
    "brands": {
      "brand": [
        "DAN"
      ]
    },
    "code": "208"
  }
]
}

我的问题是(使用Jackson注释),有没有办法避免将类名序序化为JSON ??,所以我反而会:

    "salesMarket": [{
    "brands": {
        "brand": [
            "DAN"
        ]
    },
    "code": "999"
}, {
    "brands": {
        "brand": [
            "DAN"
        ]
    },
    "code": "208"
}]

我正在考虑杰克逊在SalesMarkets上的一些注释......但是还没有成功: - (

更新:

刚刚意识到SalesMarket类是从另一个类引用的 - 这就是“salesMarkets”出现在JSON中的原因。有没有办法注释SalesMarkets字段,以便忽略它而不是包含在那里的字段?:

@XmlRootElement(name = "product")
public class Product {

@XmlElement(required = true)
protected String propertyID;
@XmlElement(required = true)
protected String season;
**protected SalesMarkets salesMarkets;**
protected Information information;
protected Features features;
protected Location location;
protected Address address;
protected Buildings buildings;
protected Pictures pictures;
protected Media media;
protected Prices prices;
protected Offers offers;
protected Availabilities availabilities;
protected Services services;
protected Concepts concepts;
...

1 个答案:

答案 0 :(得分:6)

您需要删除

@XmlRootElement(name = "salesMarkets")

或在the feature上停用ObjectMapper

objectMapper.configure(SerializationConfig.Feature.WRAP_ROOT_VALUE, true)

要在salesMarkets个实例中进一步展开 Product字段,您可以执行以下操作:

public class Product {
  protected SalesMarkets salesMarkets;

  public List<SalesMarket> getSalesMarkets(){
     if(salesMarkets != null){
       return salesMarkets.getSalesMarket();
     } else {
       return null;
     }
  }
}