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 객체 또는 배열을 Jackson의 일반 JSON 트리 모델로 읽을 수있게 해줍니다. 이 작업을 수행하면 파일에 나타나는 순서 (예 : field1과 field2가 항상 같은 순서는 아님)에 관계없이 데이터에 임의로 액세스 할 수 있습니다. Jackson은 자신 만의 Java 객체에도 매핑을 지원합니다. jp.skipChildren()은 편리합니다. 포함 된 모든 이벤트에서 자신을 실행하지 않고도 전체 객체 트리 또는 배열을 건너 뛸 수 있습니다.
Java EE 대안 : javax.json.stream.JsonParser – xonya