问题
public class ResponseList implements Serializable {
private String sku;
private String query;
private List<QAResponse> responses;
// getter and setter
}
The 2nd class:
public class QAResponse implements Serializable {
private AnswerLevel answerLevel;
private double similarity;
private String question;
private String dataSource;
private String answer;
private String ensembleFlag;
// getter and setter
}
My JSON (jsonOutput):
{
"sku":"4265252",
"query":"\u8fd9\u6b3e\u662f\u5927\u4e00\u5339\u7684\u5440",
"QAResponse":[
{
"answerLevel":"L1",
"similarity":"1.217891",
"question":"\u51e0\u5339\u7684",
"dataSource":"knowledge",
"ensembleFlag":"YES",
"answer":"1\u5339\u7684"
}
}
Then why does my JSON object mapper failed?
ResponseList responseList = null;
if (jsonOutput != null) {
ObjectMapper mapper = new ObjectMapper();
try {
responseList = mapper.readValue(jsonOutput, ResponseList.class);
} catch (IOException io) {
LOGGER.error(" json mapping to Java object failed!");
io.printStackTrace();
}
}
The error message:
com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "QAResponse" (class com.jnlu.qe.model.ResponseList), not marked as ignorable (3 known properties: "query", "responses", "sku"])
at [Source: (String)"{"sku": "4265252", "query": "\u8fd9\u6b3e\u662f\u5927\u4e00\u5339\u7684\u5440", "QAResponse": [{"answerLevel": "L1", "similarity": "1.217891", "question": "\u51e0\u5339\u7684", "dataSource": "knowledge", "ensembleFlag": "YES", "answer": "1\u5339\u7684"}, {"answerLevel": "L1", "similarity": "1.193976", "question": "\u8fd9\u4e2a\u662f\u51e0\u5339\u7684", "dataSource": "knowledge", "ensembleFlag": "YES", "answer": "\u8fd9\u6b3e\u662f1\u5339\u7684"}, {"answerLevel": "L1", "similarity": "1.179149", ""[truncated 8542 chars]; line: 1, column: 96] (through reference chain: com.jnlu.qe.model.ResponseList["QAResponse"])
Why doesn't the "QAResponse" not recognized?
回答1:
Its throwing exception because in json input "QAResponse" property not exist. If you don't want to change responses into class then add @JsonProperty annotation.
@JsonProperty(value = "QAResponse")
private List<QAResponse> responses;
回答2:
Wrong field name in the ResponseList
class, instead:
private List<QAResponse> responses;
it should be:
private List<QAResponse> QAResponse;
However QAResponse.answerLevel
field should most likely be a String
unless AnswerLevel
is an enum.
回答3:
I think that is because in the JSON a property has a name QAResponse
but in a class it is a responses
. So you must make them to have a same name
来源:https://stackoverflow.com/questions/52936445/why-does-my-json-mapper-not-recognize-my-object