在JSON对象上使用分组类型的操作

编程入门 行业动态 更新时间:2024-10-25 18:23:14
本文介绍了在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 java-8 and Gson, but you can also achieve this without it (but you'll write more code).

更多推荐

在JSON对象上使用分组类型的操作

本文发布于:2023-10-16 16:53:24,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   类型   操作   JSON

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!