简体   繁体   中英

Grouping same date JSON data together Using java

I have created one json Object Using java and it's values are given below

{
  "result":[
    {"ID":7252,"Age":52,"Date":"2015-11-25","DAY":"Wednesday","Gender":"M"},
    {"ID":7252,"Age":52,"Date":"2015-12-05","DAY":"Saturday","Gender":"M"},
    ....
  ],
  "status":"ok"
}

I need to group data as per date,required format is given below

{
  "result":[
    {"2015-11-25":[
      {"ID":7252,"Age":52,"Date":"2015-11-25","DAY":"Wednesday","Gender":"F"},
      {"ID":7252,"Age":52,"Date":"2015-11-25","DAY":"Wednesday","Gender":"M"}
    ]},
    {"2015-10-25":[
      {"ID":7252,"Age":52,"Date":"2015-10-25","DAY":"Tuesday","Gender":"F"},
      {"ID":7252,"Age":52,"Date":"2015-10-25","DAY":"Tuesday","Gender":"M"}
    ]},
  ],
  "status":"ok"
}

Basically i need group all same date data together inside JSON with date as key How can i achieve this JSON format using java

What kind of JSON mapper do you use? Jackson, GSON, ...?

And please provide some code. So we can see what you're doing.


If you created the JSON object using Java, you should have a Java Object structure, right?

Something like this:

class Data {
  int id;
  int age;
  LocalDate date;
  ...
}

And somewhere an Array / List of your data:

List<Data> result = new ArrayList<>();
result.add(data1);
result.add(data2);
result.add(data3);

Then you can use Java8 Stream API to group your data:

Map<LocalDate, Data> grouped = result
    .stream()
    .collect(
        Collectors.groupingBy(Data::getDate)
    );

The result will be a Map . Your result should be a List .

So you should be able to simply iterate over the Map and insert it into a new List .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM