As shown in title, I want to convert JSONArray (defined in "splits" field) to JSON fields using Java. I couldn’t find a similar topic here, if I missed something please let me know.
Bit of my JSON is shown below:
{
"carId": 1001,
"driverIndex": 0,
"laptime": 173001,
"isValidForBest": false,
"splits": [
91851,
52002,
29147
]
},
{
"carId": 1001,
"driverIndex": 0,
"laptime": 107270,
"isValidForBest": true,
"splits": [
26295,
51960,
29015
]
}
I want to achieve something like this:
{
"carId": 1001,
"driverIndex": 0,
"laptime": 173001,
"isValidForBest": false,
"sector1": 91851,
"sector2": 52002,
"sector3": 29147
},
{
"carId": 1001,
"driverIndex": 0,
"laptime": 107270,
"isValidForBest": true,
"sector1": 26295,
"sector2": 51960,
"sector3": 29015
}
I found some ways to solve it by parsing array to a new object, but I don’t want to create it if possible, because another object would make further code much more complicated and I want it to be as simple as possible. Values in "splits" field are also not used anywhere else.
I tried using JsonNode and ObjectNode from package com.fasterxml.jackson.databind, but there were problems with converting from ArrayNode to ObjectNode and nothing found on web was helpful.
2
Answers
You can iterate through the JSONArray, extract the individual values, and add them as separate fields in the existing JSON objects:
assuming that the input is an Array of cards