在JSON对象上使用分组类型的操作 [英] Using group-by type of operation on JSON objects

查看:183
本文介绍了在JSON对象上使用分组类型的操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下格式的JSON数据。

  [{
id:16966,
post:这是关于道路的!,
category:道路,
},


。]

我想根据类别对JSON条目进行分组。因此,我将在一个数据结构中获取所有与道路相关的条目,(如列表)。我知道我可以将数据放入Mongo DB甚至关系数据库中并查询。如果不这样做,是否有一些简单的方法来做到这一点? 解决方案

如果您要读取整个JSON文件,首先将所有条目读入 List< Data> ,然后将它们分组到

  class Data {
private int id;
private String post;
私有字符串类别;

// getter,equals,hashcode,toString等
}

然后:

  public class Test {
public static void main(String args [])throws异常{
Gson gson = new Gson();
清单<资料> list = gson.fromJson(new BufferedReader(new FileReader(myJson.json)),new TypeToken< List< Data>>(){}。getType());
地图< String,List< Data>> groupedMap = list.stream()。collect(Collectors.groupingBy(Data :: getCategory)); (k,v) - > System.out.println(k +=>+ v));


输出:

  road =>数据[id = 16966,post =这是关于road !, category = road],Data [id = 16965,post =这是关于road !, category = road]] 
land => [数据[id = 16961,post =这是关于土地!,category = land]]

I在文件中添加了一些条目。我想你也可以编写自己的反序列化器,以便在你有一个临时列表并直接存储在地图中时摆脱这一步骤,但是你问了一个简单的方法:-)。另请注意,我正在使用 java-8 和Gson,但你也可以在没有它的情况下实现它(但你会写更多的代码)。

I have JSON data in the following format.

 [{
    "id": 16966,
    "post": "This is about road!",
    "category": "road",
},
.
.
.]

I want to group JSON entries according to their categories. So, I will get all road related entries in one datastructure, (say list). I know that I can put the data into Mongo DB or even a relational database and do querying. Without doing that, is there some easy method to do this?

解决方案

If you gonna read the entire JSON file, an easy way is to first read all the entries into a List<Data> and then group them in a Map<String, List<Data>>.

class Data {
    private int id;
    private String post;
    private String category;

    //getter, equals, hashcode, toString, etc.
}

and then:

public class Test {    
    public static void main(String args[] ) throws Exception {
        Gson gson = new Gson();
        List<Data> list = gson.fromJson(new BufferedReader(new FileReader("myJson.json")), new TypeToken<List<Data>>(){}.getType());
        Map<String, List<Data>> groupedMap = list.stream().collect(Collectors.groupingBy(Data::getCategory));

        groupedMap.forEach((k, v) -> System.out.println(k + " => " + v));
    }    
}

which outputs:

road => [Data [id=16966, post=This is about road!, category=road], Data [id=16965, post=This is about road!, category=road]]
land => [Data [id=16961, post=This is about land!, category=land]]

I added some entries to the file. I guess you could write your own deserializer too to get rid of the step when you have a temporary list and store directly in the map, but you asked for an easy way :-). Also note that I'm using and Gson, but you can also achieve this without it (but you'll write more code).

这篇关于在JSON对象上使用分组类型的操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆