Jackson Apiストリーミングとツリーモデルの解析オプションを組み合わせることは非常に簡単です:ファイル全体をストリーミング形式で移動し、個々のオブジェクトをツリーに読み込むことができます構造。 exampleとして
、のは、以下の入力をみましょう:
{
"records": [
{"field1": "aaaaa", "bbbb": "ccccc"},
{"field2": "aaa", "bbb": "ccc"}
] ,
"special message": "hello, world!"
}
はフィールドだけがスパースである、またはレコードは、より複雑な構造を有する想像してみてください。
次のスニペットは、ストリームとツリーモデルの解析の組み合わせを使用してこのファイルを読み取る方法を示しています。個々のレコードはツリー構造で読み込まれますが、ファイル全体がメモリに読み込まれることはありません。そのため、最小限のメモリを使用しながら、1ギガバイトの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オブジェクトまたは配列をJacksonのジェネリックJSONツリーモデルに読み込むことを可能にします。一度これを行うと、ファイルに表示される順序に関係なく、ランダムにデータにアクセスできます(この例では、field1とfield2は必ずしも同じ順序ではありません)。 Jacksonは独自のJavaオブジェクトへのマッピングもサポートしています。 jp.skipChildren()は便利です。完全なオブジェクトツリーまたは配列を、そのオブジェクトに含まれるすべてのイベントで実行する必要なしにスキップできます。
Java EE代替:javax.json.stream.JsonParser – xonya