JsonNode Jackson의 나무 모델입니다. JSON의 경우 JSON을 JsonNode 인스턴스로 읽고 JsonNode를 JSON에 쓸 수 있습니다. ObjectMapper 를 생성하여 Jackson을 사용하여 JSON을 JsonNode로 읽으려면 인스턴스를 만들고 readValue()를 호출합니다. 방법. 필드, 배열에 액세스할 수 있습니다. 또는 중첩된 개체 get() 사용 JsonNode 메소드 수업. asText()를 사용하여 유효한 문자열 표현을 반환할 수 있습니다. 메소드 및 노드의 값을 Java int로 변환 asInt() 사용 JsonNode 메소드 수업.
아래 예에서는 JsonNode의 JSON 필드, 배열 및 중첩 개체에 액세스할 수 있습니다.
예시
import com.fasterxml.jackson.databind.*;
import java.io.*;
public class ParseJSONNodeTest {
public static void main(String args[]) {
String jsonStr = "{ \"name\" : \"Raja\", \"age\" : 30," +
" \"technologies\" : [\"Java\", \"Scala\", \"Python\"]," +
" \"nestedObject\" : { \"field\" : \"value\" } }";
ObjectMapper objectMapper = new ObjectMapper();
try {
JsonNode node = objectMapper.readValue(jsonStr, JsonNode.class);
JsonNode nameNode = node.get("name");
String name = nameNode.asText();
System.out.println(name);
JsonNode ageNode = node.get("age");
int age = ageNode.asInt();
System.out.println(age);
JsonNode array = node.get("technologies");
JsonNode jsonNode = array.get(1);
String techStr = jsonNode.asText();
System.out.println(techStr);
JsonNode child = node.get("nestedObject");
JsonNode childField = child.get("field");
String field = childField.asText();
System.out.println(field);
} catch (IOException e) {
e.printStackTrace();
}
}
} 출력
Raja 30 Scala value