从文本文件中读取多个JSON对象 [英] Read Multiple JSON object from a Text File

查看:827
本文介绍了从文本文件中读取多个JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题类似于此处
几点:

My Question is similar to what has been asked here . few points :


  1. 我无法更改格式。 (没有逗号被添加等)

  2. 这基本上是一个包含1000个Json对象的巨大.txt文件。

  3. 我的Json对象很大。

这就是我现在正在做的事情:

This is what I am doing right now :

    FileReader fileReader = new FileReader(fileName);
        BufferedReader reader = new BufferedReader(fileReader);
        String data = "";
        while((data = reader.readLine()) != null){
            ObjectMapper mapper = new ObjectMapper();
            Map<String,String> map = mapper.readValue(data, Map.class);
        }

目前我正在使用Jackson,理想情况下我想从中读取一个Json对象一次解压文件,然后转到下一个文件。我需要从这些Json对象中统计出唯一的id号,并执行更多操作。最好一一阅读。

Currently I am using Jackson and Ideally I would like to read one Json Object from the file at a time, Parse it and then move on to the next one. I need to count let say unique number of id's from these Json object and do more operations. It will be best to read them one by one.

杰克逊是未来最好的方式吗?
这是一个解析巨大Json的好例子,但它只处理每个文件一个对象。我的文件有巨大的Jsons(其中有1000个)。

Is jackson would be the best way going forward ? This is a good example of parsing huge Json, But it deals with only one object per file. My file has huge Jsons (1000s of them).

推荐答案

这是一个适合我的杰克逊例子。我在单个json文件中有数千个json对象(令牌)。此代码将遍历文件读取每个令牌并打印它的序列。

Here is a Jackson example that works for me. I have thousands json objects (tokens) in a single json file. This code will iterate through the file read each token and print it's serial.

必需的导入:

Required imports:

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.ObjectMapper;

使用Jackson从 FileInputStream :

Using Jackson to read multiple json objects from FileInputStream:

try (FileInputStream fis = new FileInputStream("D:/temp/tokens.json")) {
        JsonFactory jf = new JsonFactory();
        JsonParser jp = jf.createParser(fis);
        jp.setCodec(new ObjectMapper());
        jp.nextToken();
        while (jp.hasCurrentToken()) {
            Token token = jp.readValueAs(Token.class);
            jp.nextToken();
            System.out.println("Token serial "+token.getSerialNumber());
        }
    }

这篇关于从文本文件中读取多个JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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