为什么我的 JSON 映射器无法识别我的对象?

Why does my JSON mapper not recognize my object?

public class ResponseList implements Serializable {

    private String sku;

    private String query;

    private List<QAResponse> responses;
    // getter and setter
}

第二个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
}

我的 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"
      }
}

那为什么我的 JSON 对象映射器失败了?

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();
    }
}

错误信息:

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?

我认为这是因为在 JSON 中,属性 的名称是 QAResponse,但在 class 中,它是 responses。所以你必须让他们有相同的名字

ResponseList class 中的字段名称错误,而是:

private List<QAResponse> responses;

应该是:

private List<QAResponse> QAResponse;

但是 QAResponse.answerLevel 字段很可能是 String 除非 AnswerLevel 是一个枚举。

它抛出异常,因为在 json 中输入 "QAResponse" 属性 不存在。如果您不想将响应更改为 class,请添加 @JsonProperty 注释。

@JsonProperty(value = "QAResponse")
private List<QAResponse> responses;