如何流式传输 json 对象中的 Json 数组?

How do I Stream a Json array that is within a json object?

我有一个非常大的 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 对象,则整个对象将加载到一个包含数组的对象中,但我想将数组流出。

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

有更好的方法吗?

不幸的是,无法更改源,我必须使用它。

谢谢! 丹尼尔

我用 Jackson 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();
            }

        }

谢谢!