杰克逊对象阵列

时间:2014-02-02 19:33:33

标签: java json jackson

我有以下JSON:

[
  {
    "id": 3589954,
    "type": "e",
    "pos": 1
  },
  {
    "id": 3837014,
    "type": "p",
    "pos": 2
  }
]

以及以下Java类:

public class Business {

private int idBusiness;

private String type;

private int pos;

public Business(int idBusiness, String type, int pos) {
    this.idBusiness = idBusiness;
    this.type = type;
    this.pos = pos;
}

// getters & setters .........
}

我试图将其读作:

businessList = mapper.readValue(strBusinessIDArrayJSON, new TypeReference<List<Business>>(){});

我无法读取JSON - 调用后我得到businessList = null。这样做的正确方法是什么。

2 个答案:

答案 0 :(得分:1)

我很惊讶你得到null而不是一堆例外。(我假设你正在吞下例外情况。)

您需要一个无参数构造函数,或者您需要使用@JsonProperty注释当前构造函数中的参数,并使用它们应映射到的JSON元素的名称。它可能看起来像

public Business(@JsonProperty("id") int idBusiness, @JsonProperty("type") String type,@JsonProperty("pos") int pos) {
    this.setId(idBusiness);
    this.type = type;
    this.pos = pos;
}

请注意,JSON包含属性id,而不是idBusiness,因此您需要@JsonProperty("id")字段,getter或setter(或重命名字段及其getter / setter) )。

答案 1 :(得分:1)

您应该更好地命名您的财产:

private int id;

或者,您可以在“idBusiness”

上使用@JsonProperty(value="id")作为注释