我有以下 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。正确的做法是什么?
最佳答案
我很惊讶你得到了 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)。
关于java - jackson 对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21515195/