Reputation: 344
I have a json string as below
{
"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"
}
]
}
}
I need to extract all nodes and values under "errors". This is my current piece of code
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);
}
How do I get the node name?
Upvotes: 0
Views: 2953
Reputation: 47895
The following code ...
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);
}
}
... will print out:
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
The key difference between this and the code you posted is the JsonPath expression. You were using: $..errors
which produces something like:
[
null,
[
{...}
],
null
]
So, there's more than one node to walk through in order to find the one of interest to you, By contrast, this expression: returns only the errors
array e.g.
[
{...}
]
Upvotes: 1