我有一个json字符串,如下所示
{
"haserrors":
{
"errornumber": "400",
"errors": [
{
"nameofbusiness-error-1": "nameofbusiness must have a length greater than 1",
"nameofbusiness-error-2": "legalname must have a length greater than 1",
"nameofbusiness-error-3": "postaladdress must have a length greater than 1",
"nameofbusiness-error-4": "city must have a length greater than 1",
"nameofbusiness-error-5": "state must have a length greater than 1",
"nameofbusiness-error-6": "pincode must have a length greater than 6, pincode must be numeric, pincode must be positive",
"nameofbusiness-error-7": "fewwords must have a length greater than 1",
"nameofbusiness-error-8": "lob must have a length greater than 1",
"nameofbusiness-error-9": "step must be numeric, step must be positive"
}
]
}
}
我需要提取"错误"下的所有节点和值。这是我目前的一段代码
Configuration conf = Configuration.builder().jsonProvider(new JacksonJsonNodeJsonProvider())
.options(Option.ALWAYS_RETURN_LIST, Option.SUPPRESS_EXCEPTIONS).build();
ArrayNode jsonErrorMessageNodes = JsonPath.using(conf).parse(<<JSON STRING ABOVE>>).read("$..errors");
for (Iterator<JsonNode> it = jsonErrorMessageNodes.elements() ; it.hasNext() ; ) {
JsonNode node = it.next();
String s = node.toString();
System.out.println(node);
}
如何获取节点名称?
答案 0 :(得分:0)
以下代码......
Configuration conf = Configuration.builder().jsonProvider(new JacksonJsonNodeJsonProvider())
.options(Option.ALWAYS_RETURN_LIST, Option.SUPPRESS_EXCEPTIONS).build();
ArrayNode jsonErrorMessageNodes = JsonPath.using(conf).parse(json).read("$..errors[*]");
for (Iterator<JsonNode> it = jsonErrorMessageNodes.elements() ; it.hasNext() ; ) {
JsonNode node = it.next();
for (Iterator<String> it1 = node.fieldNames(); it1.hasNext(); ) {
final String s = it1.next();
System.out.println(s);
}
}
...将打印出来:
nameofbusiness-error-1
nameofbusiness-error-2
nameofbusiness-error-3
nameofbusiness-error-4
nameofbusiness-error-5
nameofbusiness-error-6
nameofbusiness-error-7
nameofbusiness-error-8
nameofbusiness-error-9
这与您发布的代码之间的主要区别在于JsonPath表达式。您使用的是$..errors
,其产生的内容如下:
[
null,
[
{...}
],
null
]
因此,为了找到您感兴趣的节点,需要遍历多个节点,相反,此表达式:仅返回 errors
数组,例如
[
{...}
]