[英]Using Jackson to parse a escaped json to JsonNode
I want to parse an escaped child json within a parent json.我想在父 json 中解析一个转义的子 json。 Right now I am using
StringEscapeUtils.unescapeJava
to first unescape the string.现在我正在使用
StringEscapeUtils.unescapeJava
首先对字符串进行转义。 Then I am passing the unescaped string to objectMapper.readTree
to get a JsonNode object.然后我将未转义的字符串传递给
objectMapper.readTree
以获取 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.当我使用 Jackson 并读取
child
节点的值时,它会在其周围添加引号。 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.我觉得应该有更好的方法来处理这个用例,但我可能是错的。
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());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.