Reputation: 3090
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.
Upvotes: 8
Views: 6697
Reputation: 6707
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());
Upvotes: 7