使用 Jackson 将转义的 json 解析为 JsonNode

Par*_*ane 5 java parsing json jackson deserialization

我想解析父 json 中的转义子 json。现在我用来StringEscapeUtils.unescapeJava首先取消转义字符串。然后我将未转义的字符串传递给以objectMapper.readTree获取 JsonNode 对象。

{
    "fileName": "ParentJson",
    "child": "{\"fileName\":\"ChildJson\",\"Description\":\"Extract string value at child node and convert child json to JsonNode object using only Jackson.\"}"
}
Run Code Online (Sandbox Code Playgroud)


当我使用 Jackson 并读取节点的值时child,它会在其周围添加引号。我不知道这是否是预期的行为。所以我必须先删除这些引号。

String childString = StringEscapeUtils.unescapeJava(parent.get("child").toString());
childString = StringUtils.removeStart(StringUtils.removeEnd(childString, "\"") , "\"");
JsonNode child = objectMapper.readTree(childString);
Run Code Online (Sandbox Code Playgroud)

我觉得应该有更好的方法来处理这个用例,但我可能是错的。

Sim*_* G. 4

你这样做:

    String sampleText = "{\n"
        + "    \"fileName\": \"ParentJson\",\n"
        + "    \"child\": \"{\\\"fileName\\\":\\\"ChildJson\\\",\\\"Description\\\":\\\"Extract string value at child node and convert child json to JsonNode object using only Jackson.\\\"}\"\n"
        + "}";
    ObjectMapper objectMapper = new ObjectMapper();
    JsonNode parentJson = objectMapper.readTree(sampleText);
    JsonNode childNode = parentJson.get("child");
    String childText = childNode.asText();
    JsonNode childJson = objectMapper.readTree(childText);
    System.out.println(childJson);
    System.out.println("fileName    = " + childJson.get("fileName").asText());
    System.out.println("Description = " + childJson.get("Description").asText());
Run Code Online (Sandbox Code Playgroud)