简体   繁体   English

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

[英]Using group-by type of operation on JSON objects

I have JSON data in the following format. 我有以下格式的JSON数据。

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

I want to group JSON entries according to their categories. 我想根据其类别对JSON条目进行分组。 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. 我知道我可以将数据放入Mongo DB或关系数据库中并进行查询。 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>> . 如果您要读取整个JSON文件,一种简单的方法是先将所有条目读取到List<Data> ,然后将它们分组在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). 还要注意,我正在使用和Gson,但是如果没有它,您也可以实现这一点(但是您将编写更多代码)。

Take a look on JXPath. 看一下JXPath。 This library allows running XPath queries on collections of java objects. 该库允许对Java对象集合运行XPath查询。 So, you can map JSON to your java model using one of popular JSON parser (eg Jackson or Gson) and then JXPath to run XPath queries on your collection. 因此,您可以使用流行的JSON解析器(例如Jackson或Gson)之一,然后使用JXPath将JSON映射到Java模型,以对集合运行XPath查询。

For more information refer here: http://commons.apache.org/proper/commons-jxpath/ 有关更多信息,请参见此处: http : //commons.apache.org/proper/commons-jxpath/

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

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