JSON解析器通过大型JSON文件的条目读取条目 [英] JSON parser read an entry by entry from large JSON file

查看:233
本文介绍了JSON解析器通过大型JSON文件的条目读取条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个巨大的JSON文件(1GB),它基本上是以下格式的对象数组:

$ $ p $ [{ x:y,p:q},{x1:y1,p1:q1},....]

我想解析这个文件,所有的数据都不会被加载到内存中。

基本上我想得到如:数组中的前1000个对象对内存进行处理,然后将下一个1000个对象放入内存进程中,等等util所有数据都被读取。

是否有任何支持此用例的JSON库?我目前使用 Gson 。然而,当我调用 gson.fromJson()



时,它会将所有数据加载到内存中。 。

解决方案

使用杰克逊,你可以使用类似SAX的方法(流)使用 JsonParser 对象,在你的情况下它会是这样的:

  JsonFactory jsonFactory = new JsonFactory(); 
JsonParser parser = jsonFactory.createParser(new File(/ path / to / my / jsonFile));

//映射每个对象存储字段值对的位置
Map< String,String> fields = new HashMap< String,String>();

JsonToken令牌; $()($ = $)$($)$($)$ {

//开始一个新的对象,清除地图
case START_OBJECT:
fields.clear();
休息;

//对于每个字段值对,将其存储在地图'fields'中
case FIELD_NAME:
String field = parser.getCurrentName();
token = parser.nextToken();
String value = parser.getValueAsString();
fields.put(field,value);
休息;

//使用字段值对做些事
case END_OBJECT:
doSomethingWithTheObject(fields)
break;
}
}
parser.close();


I have a huge JSON file (1GB) which is basically an array of objects in the below format

[{"x":"y", "p":"q"}, {"x1":"y1", "p1":"q1"},....]

I want to parse this file such the all the data is not loaded in memory.
Basically I want to get for eg: first 1000 objects in the array to memory process it and then get the next 1000 objects into the memory process it and so on util all data is read.
Is there any JSON library that supports this use case? I currently use Gson. However it loads all the data to memory when I call gson.fromJson()

Thanks in advance for the help.

解决方案

With Jackson you can use a SAX-like approach (streaming) using a JsonParser object, in your case it would be something like this:

JsonFactory jsonFactory = new JsonFactory();
JsonParser parser = jsonFactory.createParser(new File("/path/to/my/jsonFile"));

// Map where to store your field-value pairs per object
Map<String, String> fields = new HashMap<String, String>();

JsonToken token;
while ((token = parser.nextToken()) != JsonToken.END_ARRAY) {
    switch (token) {

        // Starts a new object, clear the map
        case START_OBJECT:
            fields.clear();
            break;

        // For each field-value pair, store it in the map 'fields'
        case FIELD_NAME:
            String field = parser.getCurrentName();
            token = parser.nextToken();
            String value = parser.getValueAsString();
            fields.put(field, value);
            break;

        // Do something with the field-value pairs
        case END_OBJECT:
            doSomethingWithTheObject(fields)
            break;
        }
    }
    parser.close();

这篇关于JSON解析器通过大型JSON文件的条目读取条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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