简体   繁体   English

使用Java将同一日期JSON数据分组在一起

[英]Grouping same date JSON data together Using java

I have created one json Object Using java and it's values are given below 我已经使用Java创建了一个json对象,其值如下所示

{
  "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 基本上我需要将所有相同的日期数据一起组合在JSON中,并且以日期为键。如何使用Java实现此JSON格式

What kind of JSON mapper do you use? 您使用哪种JSON映射器? Jackson, GSON, ...? 杰克逊,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? 如果使用Java创建了JSON对象,则应该具有Java Object结构,对吗?

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: 然后,您可以使用Java8 Stream API对数据进行分组:

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

The result will be a Map . 结果将是Map Your result should be a List . 您的结果应为List

So you should be able to simply iterate over the Map and insert it into a new List . 因此,您应该能够简单地遍历Map并将其插入新的List

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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