【问题标题】:Using Jackson to parse a escaped json to JsonNode使用 Jackson 将转义的 json 解析为 JsonNode
【发布时间】:2020-06-10 17:13:46
【问题描述】:

我想在父 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.\"}"
}


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

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

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

【问题讨论】:

    标签: java json parsing jackson deserialization


    【解决方案1】:

    你这样做:

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

    【讨论】:

    • 好的!让我试试这个。 .toString().asText() 有区别吗?
    • 是的 - .toString() 为您提供 JSON 表示,如果节点是文本节点,asText() 为您提供实际值。
    猜你喜欢
    • 2011-04-08
    • 2017-01-16
    • 1970-01-01
    • 2014-05-23
    • 1970-01-01
    • 1970-01-01
    • 2020-12-10
    相关资源
    最近更新 更多