0

我有一个非常大的 Json 需要流式传输和解析。源代码如下所示:

{
    "Report_Entry": [{
            "FirstName": "Brett",
            "Position": "13_Delta Corp",
            "Worker": "Mr Battles"
        },
        {
            "FirstName": "Dan",
            "Position": "13_Delta Corp",
            "Worker": "Mr Brown"
        }]
}

我想做这样的事情:

InputStream inStream = null;
JsonReader reader = null;
Gson gson = null;

gson = new Gson();
inStream = new FileInputStream("C:\\Downloads\\largereportdata.json");

reader = new JsonReader(new InputStreamReader(inStream, "UTF-8"));
List<Message> messages = new ArrayList<Message>();
reader.beginArray();
while (reader.hasNext()) {
    Message message = gson.fromJson(reader, Message.class);
    //Process the message 
}
reader.endArray();
reader.close();

class Message{
    public String First_Name = null;
    public String Position = null;
    public String Worker = null;
}

如果我将 gson.fromJson 用于数组的父 json 对象,则整个对象将加载到 ONE 对象中,其中包含数组,但我想将数组流出。

我现在看到的唯一方法是以某种方式编辑输入并删除父“Report_Entry”和尾括号,这是一种糟糕的方法。

有更好的方法吗?

不幸的是,源无法更改,我必须解决这个问题。

谢谢!丹尼尔

4

1 回答 1

0

我使用杰克逊 API 解决了它。

JsonFactory f = new MappingJsonFactory();

        JsonParser jp = new JsonFactory().createParser(new File("C:\\Users\\Downloads\\rootpart.json"));

        ObjectMapper mapper = new ObjectMapper();
        ReportData reportData = null;

        JsonToken current;
        current = jp.nextToken();
        if (current != JsonToken.START_OBJECT) {
            System.out.println("Error: root should be object: quitting.");
            return;
        }
        while (jp.nextToken() != JsonToken.END_OBJECT) {
            String fieldName = jp.getCurrentName();
            current = jp.nextToken();
            if (fieldName.equals("Report_Entry")) {
                if (current == JsonToken.START_ARRAY) {
                    while (current != JsonToken.END_ARRAY) {
                        if (current == JsonToken.START_OBJECT) {
                            reportData = mapper.readValue(jp, ReportData.class);
                            System.out.println(reportData.getKey());
                        }
                        current = jp.nextToken();
                    }
                } else {
                    jp.skipChildren();
                }
            } else {
                jp.skipChildren();
            }

        }

谢谢!

于 2019-02-05T03:57:42.967 回答