-1

My json looks like

 {
      "data": [
        {
         "location":"hjjh",
         "latitude":"56.65765",
         "longitude":"65.6576"
        }
             ],
     "data": [
        {
         "location":"thfh",
         "latitude":"67.65765",
         "longitude":"5.6576"
        }
            ]
    }

How could I merge the key of given json to single key as in below format using JAVA

{
  "data": [
    {
     "location":"hjjh",
     "latitude":"56.65765",
     "longitude":"65.6576"
    },
    {
     "location":"thfh",
     "latitude":"67.65765",
     "longitude":"5.6576"
    }
        ]
}

Same issue has been discussed in combine duplicate keys in json Can anyone tell me the fix in java

  • Take a look on linked question. Use `Jackson` library in the newest version. Create two classes: `Locations` and `Location.` Class `Location` should have 3 fields: `location`, `latitude`, `longitude`. Class `Locations` should have `private List locations = new ArrayList<>();` and a method annotated with `@JsonAnySetter` annotation: `private void setLocations(String name, List values)`. In body just add all `values` to `locations`. After deserialising process you should have all data in collection. – Michał Ziober Oct 12 '20 at 22:31

1 Answers1

0

I am not sure which JSON library you are using, here comes a way by Jackson to achieve what you want.

First, create a class Data with only one member - Map<String, List<Object>> and for its setter, annotated by @JsonAnySetter. Then implements customized setter as follows:

Class Data

class Data {
    private Map<String, List<Object>> map = new HashMap<>();
    public Map<String, List<Object>> getMap() {
        return map;
    }
    
    @JsonAnySetter
    public void setMap(String key, List<Object> value) {
        if (map.containsKey(key)) {
            map.get(key).add(value.get(0));
        } else {
            map.put(key, Stream.of(value.get(0)).collect(Collectors.toList()));
        }
    }
}

Code snippet
After class Data is ready, you can deserialize your given JSON string with duplicate keys to Data and serialize it to expected JSON string by following code snippet.

ObjectMapper mapper = new ObjectMapper();
Data data = mapper.readValue(jsonStr, Data.class);
         
System.out.println(mapper.writerWithDefaultPrettyPrinter()
        .writeValueAsString(data.getMap()));

Console output

{
  "data" : [ {
    "location" : "hjjh",
    "latitude" : "56.65765",
    "longitude" : "65.6576"
  }, {
    "location" : "thfh",
    "latitude" : "67.65765",
    "longitude" : "5.6576"
  } ]
}
LHCHIN
  • 3,679
  • 2
  • 16
  • 34