paulwong

以流的方式解释巨大JSON文件

https://www.ngdata.com/parsing-a-large-json-file-efficiently-and-easily/


https://sites.google.com/site/gson/streaming

http://www.acuriousanimal.com/2015/10/23/reading-json-file-in-stream-mode-with-gson.html

    public static void main(String [] args) throws IOException {
        String filePath = "C:big-data.json";
        FileInputStream in = new FileInputStream(new File(filePath));
        JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
        Gson gson = new GsonBuilder().create();
//        reader.beginObject();
//        reader.nextName();
        reader.beginObject();//跳过"{"
        while (reader.hasNext()) {
            // Read data into object model
            JsonToken jsonToken = reader.peek();
            if(jsonToken.equals(JsonToken.NAME)) {
                String name = reader.nextName();
                if(name.equalsIgnoreCase("SUMMARY")) {
//                    reader.beginObject();
                    Summary summary = gson.fromJson(reader, Summary.class);
                    logger.info(summary.toString());
                    break;
//                    reader.endObject();//跳过"}"
                }
            } /*else if(jsonToken.equals(JsonToken.BEGIN_OBJECT)) {
                reader.beginObject();
            } else if(jsonToken.equals(JsonToken.STRING)) {
                logger.info(reader.nextString());
            } else if(jsonToken.equals(JsonToken.NUMBER)) {
                logger.info(reader.nextInt() + "");
            } else if(jsonToken.equals(JsonToken.END_OBJECT)) {
                reader.endObject();
            } 
*/
//            Summary summary = gson.fromJson(reader, Summary.class);
//            break;
        }
        reader.close();
    }

posted on 2019-05-03 15:22 paulwong 阅读(518) 评论(0)  编辑  收藏 所属分类: JSON


只有注册用户登录后才能发表评论。


网站导航: