jackson 无法从JsonNode获取信息

7jmck4yq  于 2022-11-08  发布在  其他
关注(0)|答案(2)|浏览(223)

我在尝试访问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和message值。

jv4diomz

jv4diomz1#

根据注解,我假设您的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,但不是你想要的。你可能会发送错误的。

yi0zb3m4

yi0zb3m42#

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

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]"

相关问题