Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Jackson to parse a escaped json to JsonNode

I want to parse an escaped child json within a parent json. Right now I am using StringEscapeUtils.unescapeJava to first unescape the string. Then I am passing the unescaped string to objectMapper.readTree to get a JsonNode object.

{
    "fileName": "ParentJson",
    "child": "{\"fileName\":\"ChildJson\",\"Description\":\"Extract string value at child node and convert child json to JsonNode object using only Jackson.\"}"
}


When I use Jackson and read the value of child node, it adds quotes around it. I don't know if this is an expected behavior. So I have to remove those quotes first.

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

I feel like there should be a better way to handle this use case, but I could be wrong.

like image 663
Parth Tamane Avatar asked Jun 26 '26 00:06

Parth Tamane


1 Answers

You do it like this:

    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());
like image 163
Simon G. Avatar answered Jun 28 '26 14:06

Simon G.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!