skip to Main Content

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


  1. You can iterate through the JSONArray, extract the individual values, and add them as separate fields in the existing JSON objects:

    import com.fasterxml.jackson.databind.JsonNode;
    import com.fasterxml.jackson.databind.ObjectMapper;
    
    public class JSONArrayToJSONFields {
        public static void main(String[] args) {
            String jsonInput = "{n" +
                    "  "carId": 1001,n" +
                    "  "driverIndex": 0,n" +
                    "  "laptime": 173001,n" +
                    "  "isValidForBest": false,n" +
                    "  "splits": [n" +
                    "    91851,n" +
                    "    52002,n" +
                    "    29147n" +
                    "  ]n" +
                    "}";
    
            ObjectMapper mapper = new ObjectMapper();
            try {
                JsonNode rootNode = mapper.readTree(jsonInput);
    
    Login or Signup to reply.
  2. assuming that the input is an Array of cards

    JsonNode root = new ObjectMapper().readTree(jsonString);
    root.forEach(
            card -> {
                ObjectNode cardObject = (ObjectNode) card;
                ArrayNode splits = (ArrayNode) cardObject.remove("splits");
                for(int i=0; i < splits.size(); i++) {
                    cardObject.put("sector"+i, splits.get(i));
                }
            }
    );
    return root;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search