In my Spring Boot app, I am trying to read the value of the first key under dates
field in the following JSON:
{
"Data": {
"city": "Berlin",
"population": 5545156
"dates": {
"2022-08-20": 12345,
"2022-08-19": 12340,
"2022-08-18": 12300
}
}
}
I tried something using Jackson a shown below, but as the key is changed based on date, but it return null string. On the other hand, I should get the first value instead of giving key:
JsonNode jsonNode = new ObjectMapper().readTree(jsonString);
String dataString = jsonNode.findValuesAsText("dates").get(0).toString();
So, how can I get the first key's ("2022-08-20") value (12345) under dates ?
CodePudding user response:
You could use
jsonNode.findValue("dates").elements().next()
or jsonNode.findValue("dates").fields().next().getValue()
or jsonNode.findValue("dates").findValue(jsonNode.findValue("dates").fieldNames().next())