我會建議看看Jackson Api結合流和樹模型解析選項是非常簡單的:您可以通過流式傳輸整個文件,然後將單個對象讀入樹中結構體。
作爲example,我們採取以下輸入:
{
"records": [
{"field1": "aaaaa", "bbbb": "ccccc"},
{"field2": "aaa", "bbb": "ccc"}
] ,
"special message": "hello, world!"
}
試想場是稀疏或有更復雜的結構的記錄。
以下片段說明了如何使用流和樹模型解析的組合來讀取此文件。每個單獨的記錄都以樹形結構讀取,但文件從未完全讀入內存,因此可以在使用最小內存的情況下處理JSON文件的大小。
import org.codehaus.jackson.map.*;
import org.codehaus.jackson.*;
import java.io.File;
public class ParseJsonSample {
public static void main(String[] args) throws Exception {
JsonFactory f = new MappingJsonFactory();
JsonParser jp = f.createJsonParser(new File(args[0]));
JsonToken current;
current = jp.nextToken();
if (current != JsonToken.START_OBJECT) {
System.out.println("Error: root should be object: quiting.");
return;
}
while (jp.nextToken() != JsonToken.END_OBJECT) {
String fieldName = jp.getCurrentName();
// move from field name to field value
current = jp.nextToken();
if (fieldName.equals("records")) {
if (current == JsonToken.START_ARRAY) {
// For each of the records in the array
while (jp.nextToken() != JsonToken.END_ARRAY) {
// read the record into a tree model,
// this moves the parsing position to the end of it
JsonNode node = jp.readValueAsTree();
// And now we have random access to everything in the object
System.out.println("field1: " + node.get("field1").getValueAsText());
System.out.println("field2: " + node.get("field2").getValueAsText());
}
} else {
System.out.println("Error: records should be an array: skipping.");
jp.skipChildren();
}
} else {
System.out.println("Unprocessed property: " + fieldName);
jp.skipChildren();
}
}
}
}
正如您可以猜到,與nextToken()調用每次給人的下一個解析事件:啓動對象,啓動現場,啓動陣列,啓動對象,...,結束對象,...,高端磁盤陣列,...
jp.readValueAsTree()調用允許讀取當前解析位置(JSON對象或數組)到JSON的通用JSON樹模型中。一旦你有了這個,你可以隨機地訪問數據,而不管文件在文件中出現的順序(在示例中,field1和field2並不總是以相同的順序)。傑克遜也支持映射到您自己的Java對象。 jp.skipChildren()很方便:它允許跳過一個完整的對象樹或數組,而無需運行其中包含的所有事件。