I have a JsonNode result represented as:
[
{
"item": {
"type": "uri",
"value": "http://www.wikidata.org/entity/Q42442324"
},
"prop": {
"type": "uri",
"value": "http://www.wikidata.org/prop/direct/P21"
},
"itemLabel": {
"xml:lang": "en",
"type": "literal",
"value": "Kiisu Miisu"
}
},
{
"item": {
"type": "uri",
"value": "http://www.wikidata.org/entity/Q43260736"
},
"prop": {
"type": "uri",
"value": "http://www.wikidata.org/prop/direct/P21"
},
"itemLabel": {
"xml:lang": "en",
"type": "literal",
"value": "Paddles"
}
}
]
I am trying to retieve the values of the key "value" into an array list using the below code but am getting the error Cannot invoke "com.fasterxml.jackson.databind.JsonNode.findValue(String)" because the return value of "com.fasterxml.jackson.databind.JsonNode.get(int)" is null
for (int i = 0; i < resultSize; i ) {
JsonNode jsonObject = results.get(i);
if (indexRow < jsonObject.size()) {
jsonRows = Collections.singletonList(jsonObject.get(indexRow ).findValue("value").asText());
}
}
The value of variable jsonObject in the first iteration from the debugger is
{
"item": {
"type": "uri",
"value": "http://www.wikidata.org/entity/Q42442324"
},
"prop": {
"type": "uri",
"value": "http://www.wikidata.org/prop/direct/P21"
},
"itemLabel": {
"xml:lang": "en",
"type": "literal",
"value": "Kiisu Miisu"
}
}
Expected output is
[
"http://www.wikidata.org/entity/Q42442324",
"http://www.wikidata.org/entity/Q42442324",
"Kiisu Miisu",
"http://www.wikidata.org/entity/Q43260736",
"http://www.wikidata.org/prop/direct/P21",
"Paddles"
]
CodePudding user response:
You can use elements()
method and check if value key exist then add the value to list.
Smaple code
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.readTree(data);
List<String> values = new ArrayList<>();
jsonNode.forEach(jsonObject -> jsonObject.elements().forEachRemaining(valueNode -> {
if(valueNode.has("value"))
values.add(valueNode.get("value").asText());
}));
System.out.println(values);
Output:
[http://www.wikidata.org/entity/Q42442324, http://www.wikidata.org/prop/direct/P21, Kiisu Miisu, http://www.wikidata.org/entity/Q43260736, http://www.wikidata.org/prop/direct/P21, Paddles]