Java Jackson对象数组
我有以下JSON:Java Jackson对象数组,java,json,jackson,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
[
{
"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>>(){});
businessList=mapper.readValue(strBusinessIDArrayJSON,新类型引用(){});
我无法读取JSON-调用后我得到businessList=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
,因此您需要在字段、getter或setter(或重命名字段及其getter/setter)上使用@JsonProperty(“id”)
。您应该更好地命名您的属性:
private int id;
或者,您可以使用
@JsonProperty(value=“id”)
作为对“idBusiness”的注释非常有效谢谢。@AmarMond不客气。你是不是接受了例外情况?