无法从 JsonNode 获取信息

Unable to get info from JsonNode

我在尝试访问 JsonNode 中的某些信息时遇到问题。基本上,我有:

getResponse(String response) {
JsonNode rootNode = new ObjectMapper().readTree(response);

System.out.println("rootNode.asText(): " + rootNode.asText());
// OUTPUT: {"statusCode":2,"message":"[701] - [FAILED - There was an error while calling OSB - Connection refused]"}
System.out.println("rootNode.toString(): " + rootNode.toString());
// OUTPUT: "{\"statusCode\":2,\"message\":\"[701] - [FAILED - There was an error while calling OSB - Connection refused]\"}"
System.out.println("rootNode.textValue(): " + rootNode.textValue());
// OUTPUT: {"statusCode":2,"message":"[701] - [FAILED - There was an error while calling OSB - Connection refused]"}
System.out.println("rootNode.findValue(statusCode): " + rootNode.findValue("statusCode"));
// OUTPUT: null
System.out.println("rootNode.get(statusCode).asText(): " + rootNode.get("statusCode"));
// OUTPUT: null
System.out.println("rootNode.get(statusCode).asText(): " + rootNode.get("statusCode").asText());
// OUTPUT: npe
}

基本上,我正在尝试获取响应字符串中的 statusCode 和消息值。

根据评论,我假设您的 response 变量包含不寻常的 json 数据。

我尝试取消转义 json;

    String response = "\"{\\"statusCode\\":0,\\"message\\":\\"[0000] - [OK]\\"}\"";

    System.out.println("Unwanted json string: " + response);
    // output is "{\"statusCode\":0,\"message\":\"[0000] - [OK]\"}"
    // this is exactly the same what you comment
    response = response.substring(1, response.length() - 1);
    response = StringEscapeUtils.unescapeJson(response);
    // org.apache.commons.lang3.StringEscapeUtils
    System.out.println("Unescaped json string: " + response);
    // output is {"statusCode":0,"message":"[0000] - [OK]"}

    JsonNode rootNode = new ObjectMapper().readTree(response);

    System.out.println(rootNode.get("statusCode")); // will print 0
    System.out.println(rootNode.get("message")); // will print "[0000] - [OK]"

最好的选择是调查您得到错误 json 数据的原因。它是有效的 json 但不是你想要的。你可能发错了。

谢谢你,伙计。 我昨天通过这样做解决了问题(我还创建了一个新的 class):

JsonNode rootNode = mapper.readTree(response);
submitTransactionResponse = new ObjectMapper().readValue(rootNode.asText(), SubmitTransactionResponse.class);
System.out.println(submitTransactionResponse.getStatusCode()); // print 0
System.out.println(submitTransactionResponse.getMessage()); // print "[0000] - [OK]"