我在使用 Jackson
库反序列化 JSON 字符串并将其映射到 POJO
时遇到问题。
我有这个 json:
[{
"requestor": "Nick Jagger",
"smtp": "test@email.com",
"smtp_from": "test2@email.com",
"cnname": "testcn",
"date": "2014-11-11",
"system_ciid": "3926598",
"request_base64": "its some base64 hash"
}, {
"requestor": "Freddie Mercury",
"smtp": "test@email.com",
"smtp_from": "test2@email.com",
"cnname": "testowe cn",
"date": "2014-11-26",
"system_ciid": "JK19",
"request_base64": "some base64 hash"
}]
我创建了 POJO 类来表示该数组中的一个元素:
public class Questionareimplements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
@JsonProperty("cnname")
private String caName;
@JsonProperty("smtp")
private String smtp;
@JsonProperty("requestor")
private String issuer;
@JsonProperty("system_ciid")
private String system_ciid;
@JsonProperty("date")
private String date;
@JsonProperty("request_base64")
private String base64String;
@JsonProperty("smtp_from")
private String smtp2;
// getters and setters
}
以及代表这些对象列表的类:
public class QuestionareList {
private List<Questionare> questionares;
public List<Questionare> getQuestionares() {
return questionares;
}
public void setQuestionares(List<Questionare> questionares) {
this.questionares = questionares;
}
}
现在我如何映射这些
QuestionareList listQ = new QuestionareList();
ObjectMapper m = new ObjectMapper();
listQ = m.readValue(jsonString,QuestionareList.class);
我得到的是:
Can not deserialize instance of com.test.service.QuestionareList out of START_ARRAY token
at [Source: java.io.StringReader@27d525; line: 1, column: 1]
知道我做错了什么吗?
最佳答案
我认为你已经有 2 个 jar ,即 1. jackson 核心 2. jackson ·麦普
从 JSON 解析到 POJO
ObjectMapper mapper = new ObjectMapper();
JavaType javaType=mapper.getTypeFactory().constructCollectionType(List.class,Questionare.class);
QuestionareList listQ = new QuestionareList();
listQ.setQuestionares(mapper.readValue(jsonString,javaType));
或者我们是否可以按照您的方式做到
ObjectMapper mapper = new ObjectMapper();
JavaType javaType=mapper.getTypeFactory().constructType(QuestionareList.class);
QuestionareList listQ = new QuestionareList();
listQ = mapper.readValue(jsonString,javaType);
就是这样!
关于java - 反序列化时 Jackson JSON 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20322415/