Jackson-퀵 가이드

Jackson은 Java 객체를 JSON으로 직렬화하거나 그 반대로 직렬화하는 간단한 Java 기반 라이브러리입니다.

풍모

  • Easy to use. -jackson API는 일반적으로 사용되는 사용 사례를 단순화하기 위해 높은 수준의 파사드를 제공합니다.

  • No need to create mapping. -jackson API는 직렬화 할 대부분의 개체에 대한 기본 매핑을 제공합니다.

  • Performance. -jackson은 조용하고 빠르며 메모리 공간이 적으며 대형 개체 그래프 또는 시스템에 적합합니다.

  • Clean JSON. -jackson은 읽기 쉬운 깔끔하고 간결한 JSON 결과를 생성합니다.

  • No Dependency. -jackson 라이브러리에는 jdk 외에 다른 라이브러리가 필요하지 않습니다.

  • Open Source -jackson 라이브러리는 오픈 소스이며 무료로 사용할 수 있습니다.

JSON을 처리하는 세 가지 방법

Jackson은 JSON을 처리하는 세 가지 대체 방법을 제공합니다.

  • Streaming API-JSON 콘텐츠를 개별 이벤트로 읽고 씁니다. JsonParser는 데이터를 읽는 반면 JsonGenerator는 데이터를 씁니다. 세 가지 중에서 가장 강력한 접근 방식이며 오버 헤드가 가장 낮고 읽기 / 쓰기 작업이 가장 빠릅니다. Analogus to Stax XML 파서입니다.

  • Tree Model-JSON 문서의 메모리 내 트리 표현을 준비합니다. JsonNode 노드의 ObjectMapper 빌드 트리입니다. 가장 유연한 접근 방식입니다. XML 용 DOM 파서와 유사합니다.

  • Data Binding -속성 접근자를 사용하거나 주석을 사용하여 JSON을 POJO (Plain Old Java Object)간에 변환합니다. 두 가지 유형입니다.

    • Simple Data Binding -JSON을 Java Maps, Lists, Strings, Numbers, Booleans 및 null 개체간에 변환합니다.

    • Full Data Binding -JSON을 모든 JAVA 유형으로 변환합니다.

    ObjectMapper는 두 가지 유형의 데이터 바인딩 모두에 대해 JSON을 읽고 씁니다. 데이터 바인딩은 가장 편리한 방법이며 XML 용 JAXB 파러와 유사합니다.

옵션 온라인 시도

JAVA 기반 라이브러리 인 Guava 학습을 시작하기 위해 자체 환경을 설정할 필요가 없습니다. 이유는 매우 간단합니다. 이미 Java 프로그래밍 환경을 온라인으로 설정 했으므로 이론 작업을 수행 할 때 사용 가능한 모든 예제를 온라인에서 동시에 컴파일하고 실행할 수 있습니다. 이렇게하면 읽고있는 내용에 대한 자신감을 얻고 다른 옵션으로 결과를 확인할 수 있습니다. 모든 예제를 자유롭게 수정하고 온라인에서 실행하십시오.

다음을 사용하여 예제를보십시오 Try it 아래 샘플 코드 상자의 오른쪽 상단 모서리에서 사용할 수있는 옵션 :

public class MyFirstJavaProgram {

    public static void main(String []args) {
       System.out.println("Hello World");
    }
}

이 자습서에 제공된 대부분의 예제에서 Try it 옵션이므로 그것을 사용하고 학습을 즐기십시오.

지역 환경 설정

여전히 Java 프로그래밍 언어에 대한 환경을 설정하려는 경우이 섹션에서는 시스템에서 Java를 다운로드하고 설정하는 방법을 안내합니다. 환경을 설정하려면 다음 단계를 따르십시오.

Java SE는 Java 다운로드 링크에서 무료로 사용할 수 있습니다 . 따라서 운영 체제에 따라 버전을 다운로드합니다.

지침에 따라 Java를 다운로드하고 .exe컴퓨터에 Java를 설치합니다. 시스템에 Java를 설치 한 후에는 올바른 설치 디렉토리를 가리 키도록 환경 변수를 설정해야합니다.

Windows 2000 / XP 용 경로 설정 :

c : \ Program Files \ java \ jdk 디렉토리에 Java를 설치했다고 가정합니다 .

  • '내 컴퓨터'를 마우스 오른쪽 버튼으로 클릭하고 '속성'을 선택합니다.

  • '고급'탭에서 '환경 변수'버튼을 클릭합니다.

  • 이제 Java 실행 파일의 경로도 포함하도록 'Path'변수를 변경하십시오. 예를 들어 현재 경로가 'C : \ WINDOWS \ SYSTEM32'로 설정된 경우 경로를 'C : \ WINDOWS \ SYSTEM32; c : \ Program Files \ java \ jdk \ bin'으로 변경합니다.

Windows 95 / 98 / ME의 경로 설정 :

c : \ Program Files \ java \ jdk 디렉토리에 Java를 설치했다고 가정합니다 .

  • 'C : \ autoexec.bat'파일을 편집하고 끝에 다음 행을 추가하십시오.
    'SET PATH = % PATH %; C : \ Program Files \ java \ jdk \ bin'

Linux, UNIX, Solaris, FreeBSD에 대한 경로 설정 :

환경 변수 PATH는 Java 바이너리가 설치된 위치를 가리 키도록 설정되어야합니다. 이 작업을 수행하는 데 문제가 있으면 쉘 문서를 참조하십시오.

예를 들어 bash 를 셸로 사용하는 경우 '.bashrc : export PATH = / path / to / java : $ PATH'끝에 다음 줄을 추가합니다.

인기있는 Java 편집기 :

Java 프로그램을 작성하려면 텍스트 편집기가 필요합니다. 시장에는 훨씬 더 정교한 IDE가 있습니다. 그러나 지금은 다음 중 하나를 고려할 수 있습니다.

  • Notepad: Windows 컴퓨터에서는 메모장 (이 자습서에 권장 됨), TextPad와 같은 간단한 텍스트 편집기를 사용할 수 있습니다.

  • Netbeans:오픈 소스이며 무료로 제공되는 Java IDE입니다. http://www.netbeans.org/index.html.

  • Eclipse: 또한 Eclipse 오픈 소스 커뮤니티에서 개발 한 Java IDE이며 다음에서 다운로드 할 수 있습니다. http://www.eclipse.org/.

잭슨 아카이브 다운로드

Maven Repository-Jackson 에서 최신 버전의 Jackson jar 파일을 다운로드합니다 . 이 자습서에서는 jackson-core-2.8.9.jar, jackson-annotations-2.8.9.jar 및 jackson-databind-2.8.9.jar이 다운로드되어 C : \> jackson 폴더에 복사됩니다.

OS 아카이브 이름
윈도우 jackson-xxx-2.8.9.jar
리눅스 jackson-xxx-2.8.9.jar
jackson-xxx-2.8.9.jar

Jackson 환경 설정

설정 jackson_HOMEGuava jar가 컴퓨터에 저장된 기본 디렉토리 위치를 가리키는 환경 변수. 다음과 같이 다양한 운영 체제의 jackson 폴더에서 jackson-core-2.8.9.jar, jackson-annotations-2.8.9.jar 및 jackson-databind-2.8.9.jar을 추출했다고 가정합니다.

OS 산출
윈도우 환경 변수 jackson_HOME을 C : \ jackson으로 설정합니다.
리눅스 export jackson_HOME = / usr / local / jackson
export jackson_HOME = / Library / jackson

CLASSPATH 변수 설정

설정 CLASSPATHjackson jar 위치를 가리키는 환경 변수. 다음과 같이 다양한 운영 체제의 jackson 폴더에 jackson-core-2.8.9.jar, jackson-annotations-2.8.9.jar 및 jackson-databind-2.8.9.jar를 저장했다고 가정합니다.

OS 산출
윈도우 환경 변수 CLASSPATH를 % CLASSPATH %; % jackson_HOME % \ jackson-core-2.8.9.jar; % jackson_HOME % \ jackson-databind-2.8.9.jar; % jackson_HOME % \ jackson-annotations-2.8.9로 설정합니다. 항아리;.;
리눅스 내보내기 CLASSPATH = $ CLASSPATH :$jackson_HOME/jackson-core-2.8.9.jar:$jackson_HOME / jackson-databind-2.8.9.jar : $ jackson_HOME / jackson-annotations-2.8.9.jar :.
내보내기 CLASSPATH = $ CLASSPATH :$jackson_HOME/jackson-core-2.8.9.jar:$jackson_HOME / jackson-databind-2.8.9.jar : $ jackson_HOME / jackson-annotations-2.8.9.jar :.

jackson 라이브러리에 대해 자세히 살펴보기 전에 애플리케이션이 작동하는지 살펴 보겠습니다. 이 예에서는 Student 클래스를 만들었습니다. 학생 세부 정보가 포함 된 JSON 문자열을 만들고이를 student 객체로 역 직렬화 한 다음 JSON 문자열로 직렬화합니다.

JacksonTester라는 Java 클래스 파일을 만듭니다. C:\>Jackson_WORKSPACE.

파일 : JacksonTester.java

import java.io.IOException;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonTester {
   public static void main(String args[]){
   
      ObjectMapper mapper = new ObjectMapper();
      String jsonString = "{\"name\":\"Mahesh\", \"age\":21}";
      
      //map json to student
      try{
         Student student = mapper.readValue(jsonString, Student.class);
         
         System.out.println(student);
         
         jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(student);
         
         System.out.println(jsonString);
      }
      catch (JsonParseException e) { e.printStackTrace();}
      catch (JsonMappingException e) { e.printStackTrace(); }
      catch (IOException e) { e.printStackTrace(); }
   }
}

class Student {
   private String name;
   private int age;
   public Student(){}
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public int getAge() {
      return age;
   }
   public void setAge(int age) {
      this.age = age;
   }
   public String toString(){
      return "Student [ name: "+name+", age: "+ age+ " ]";
   }
}

Verify the result

다음을 사용하여 클래스 컴파일 javac 다음과 같이 컴파일러 :

C:\Jackson_WORKSPACE>javac JacksonTester.java

이제 jacksonTester를 실행하여 결과를 확인합니다.

C:\Jackson_WORKSPACE>java JacksonTester

출력 확인

Student [ name: Mahesh, age: 21 ]
{
  "name" : "Mahesh",
  "age" : 21
}

기억해야 할 단계

다음은 여기서 고려해야 할 중요한 단계입니다.

1 단계 : ObjectMapper 개체를 만듭니다.

ObjectMapper 객체를 만듭니다. 재사용 가능한 개체입니다.

ObjectMapper mapper = new ObjectMapper();

2 단계 : JSON을 Object로 DeSerialize합니다.

readValue () 메서드를 사용하여 JSON에서 개체를 가져옵니다. json 문자열 / json 문자열의 소스 및 개체 유형을 매개 변수로 전달합니다.

//Object to JSON Conversion
Student student = mapper.readValue(jsonString, Student.class);

3 단계 : 객체를 JSON으로 직렬화합니다.

writeValueAsString () 메서드를 사용하여 객체의 JSON 문자열 표현을 가져옵니다.

//Object to JSON Conversion		
jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(student);

ObjectMapper는 Jackson 라이브러리의 주요 행위자 클래스입니다. ObjectMapper 클래스 ObjectMapper는 기본 POJO (Plain Old Java Objects) 또는 범용 JSON 트리 모델 (JsonNode)간에 JSON을 읽고 쓰기위한 기능과 변환 수행을위한 관련 기능을 제공합니다. 또한 다양한 스타일의 JSON 콘텐츠로 작업하고 다형성 및 개체 ID와 같은 고급 개체 개념을 지원하도록 고도로 사용자 지정할 수 있습니다. ObjectMapper는 또한 고급 ObjectReader 및 ObjectWriter 클래스의 팩토리 역할도합니다.

클래스 선언

다음은에 대한 선언입니다. com.fasterxml.jackson.databind.ObjectMapper 클래스-

public class ObjectMapper
   extends ObjectCodec
      implements Versioned, Serializable

중첩 클래스

S. 아니. 클래스 및 설명
1 static class ObjectMapper.DefaultTypeResolverBuilder

소위 "기본 입력"과 함께 사용되는 유형 해석기 빌더를 제공하는 사용자 정의 된 TypeResolverBuilder (자세한 내용은 enableDefaultTyping () 참조).

2 static class ObjectMapper.DefaultTyping

enableDefaultTyping ()과 함께 사용되는 열거 형은 어떤 종류의 유형 (클래스) 기본 유형을 사용해야 하는지를 지정합니다.

필드

  • protected DeserializationConfig _deserializationConfig -직렬화 프로세스에 대한 기본 전역 설정을 정의하는 구성 개체입니다.

  • protected DefaultDeserializationContext _deserializationContext-청사진 컨텍스트 개체; 여기에 저장되어 사용자 지정 하위 클래스를 허용합니다.

  • protected InjectableValues _injectableValues -역 직렬화 된 POJO에 삽입 할 값에 대한 공급자입니다.

  • protected JsonFactory _jsonFactory -필요에 따라 JsonParser 및 JsonGenerator 인스턴스를 만드는 데 사용되는 팩토리입니다.

  • protected SimpleMixInResolver _mixIns -믹스 인 어노테이션을 적용하는 방법을 정의하는 매핑 : 키는 추가 어노테이션을 수신 할 유형이고 값은 "혼합"할 어노테이션이있는 유형입니다.

  • protected ConfigOverrides _propertyOverrides -현재 활성화 된 유형별 구성 재정의는 선언 된 속성 유형에 의해 액세스됩니다.

  • protected Set<Object> _registeredModuleTypes -등록 된 Module.getTypeId ()에 따라 모듈 유형 세트, MapperFeature.IGNORE_DUPLICATE_MODULE_REGISTRATIONS가 활성화 된 경우 추적하여 중복 등록 호출을 무시할 수 있습니다 (대부분 동일한 핸들러를 여러 번 추가하지 않도록 방지).

  • protected ConcurrentHashMap<JavaType,JsonDeserializer<Object>> _rootDeserializers -루트 레벨 디시리얼라이저를 추적하기 위해 별도의 메인 레벨 맵을 사용합니다.

  • protected SerializationConfig _serializationConfig -직렬화 프로세스에 대한 기본 전역 설정을 정의하는 구성 개체입니다.

  • protected SerializerFactory _serializerFactory -직렬 변환기를 구성하는 데 사용되는 직렬 변환기 팩토리.

  • protected DefaultSerializerProvider _serializerProvider -캐싱을 포함하여 serialization에 사용되는 serializer에 대한 액세스를 관리하는 개체입니다.

  • protected SubtypeResolver _subtypeResolver -서브 타입을 등록하고 필요에 따라 수퍼 / 서브 타입으로 해결하는 데 사용되는 것.

  • protected TypeFactory _typeFactory-JavaType 인스턴스 생성에 사용되는 특정 팩토리 모듈이 더 많은 사용자 정의 유형 처리를 추가하도록 허용하는 데 필요합니다 (대부분 비 Java JVM 언어 유형을 지원하기 위해).

  • protected static AnnotationIntrospector DEFAULT_ANNOTATION_INTROSPECTOR

  • protected static BaseSettings DEFAULT_BASE -기본 설정에는 모든 ObjectMapper 인스턴스에 사용되는 기본값이 포함됩니다.

  • protected static VisibilityChecker<?> STD_VISIBILITY_CHECKER

생성자

S. 아니. 생성자 및 설명
1 ObjectMapper()

필요에 따라 기본 JsonFactory를 생성하는 기본 생성자는 SerializerProvider를 SerializerProvider로 사용하고 BeanSerializerFactory를 SerializerFactory로 사용합니다.

2 ObjectMapper(JsonFactory jf)

필요한 JsonParsers 및 / 또는 JsonGenerator를 생성하기 위해 지정된 JsonFactory를 사용하는 인스턴스를 생성합니다.

ObjectMapper(JsonFactory jf, SerializerProvider sp, DeserializerProvider dp)

필요한 JsonParsers 및 / 또는 JsonGenerator를 생성하기 위해 지정된 JsonFactory를 사용하는 인스턴스를 생성하고, 직렬화 기 및 역 직렬화기에 액세스하기 위해 주어진 공급자를 사용합니다.

4 protected ObjectMapper(ObjectMapper src)

Copy-constructor는 주로 copy ()를 지원하는 데 사용됩니다.

행동 양식

직렬화에 사용할 SerializerProvider를 구성하는 데 사용되는 재정의 가능한 도우미 메서드입니다. void addMixInAnnotations (Class <?> target, Class <?> mixinSource)-더 이상 사용되지 않습니다. 2.5 이후 : 유창한 형식의 방법으로 대체되었습니다. addMixIn (클래스, 클래스). protected DefaultDeserializationContext createDeserializationContext (JsonParser p, DeserializationConfig cfg)-단일 루트 값을 역 직렬화하기 위해 DeserializationContext의 인스턴스를 만들기 위해 호출되는 내부 도우미 메서드입니다. JsonSchema generateJsonSchema (Class <?> t)-더 이상 사용되지 않습니다. 2.6부터 외부 JSON 스키마 생성기 (https://github.com/FasterXML/jackson-module-jsonSchema)를 사용합니다 (내부에서 acceptJsonFormatVisitor (JavaType, JsonFormatVisitorWrapper)를 호출 함) void registerSubtypes (Class <?> ... classes)- 지정된 클래스를 하위 유형으로 등록하여 유형 이름 기반 확인이 상위 유형을 하위 유형에 연결할 수 있도록하는 방법입니다 (주석을 사용하는 대신). void setFilters (FilterProvider filterProvider)-더 이상 사용되지 않습니다. 2.6 이후부터는 setFilterProvider (com.fasterxml.jackson.databind.ser.FilterProvider)를 대신 사용 (체인 허용) 지정된 문자 이스케이프 세부 정보를 출력에 사용할 ObjectReader를 구성하는 Factory 메서드를 사용합니다.
1 protected void _checkInvalidCopy(Class<?> exp)

2 protected void _configAndWriteValue(JsonGenerator g, Object value) -필요에 따라 생성기를 구성하고 쓰기 기능을 호출하기 위해 호출되는 메소드
protected Object _convert(Object fromValue, JavaType toValueType) -실제 변환 구현 : 기존의 읽기 및 쓰기 방법을 사용하는 대신 많은 코드가 인라인됩니다.
4 protected JsonDeserializer<Object> _findRootDeserializer(DeserializationContext ctxt, JavaType valueType) -전달 된 루트 수준 값에 대한 deserializer를 찾기 위해 호출되는 메서드입니다.
5 protected JsonToken _initForReading(JsonParser p) -지정된 파서가 데이터 바인딩을 위해 콘텐츠를 읽을 준비가되었는지 확인하기 위해 호출되는 메서드입니다.
6 protected ObjectReader _newReader(DeserializationConfig config) -적절한 하위 유형의 ObjectReader 인스턴스를 생성하려면 팩토리 메서드 하위 클래스를 재정의해야합니다.
7 protected ObjectReader _newReader(DeserializationConfig config, JavaType valueType, Object valueToUpdate, FormatSchema schema, InjectableValues injectableValues) -적절한 하위 유형의 ObjectReader 인스턴스를 생성하려면 팩토리 메서드 하위 클래스를 재정의해야합니다.
8 protected ObjectWriter _newWriter(SerializationConfig config) -적절한 하위 유형의 ObjectWriter 인스턴스를 생성하려면 팩토리 메서드 하위 클래스를 재정의해야합니다.
9 protected ObjectWriter _newWriter(SerializationConfig config, FormatSchema schema) -적절한 하위 유형의 ObjectWriter 인스턴스를 생성하려면 팩토리 메서드 하위 클래스를 재정의해야합니다.
10 protected ObjectWriter _newWriter(SerializationConfig config, JavaType rootType, PrettyPrinter pp) -적절한 하위 유형의 ObjectWriter 인스턴스를 생성하려면 팩토리 메소드 하위 클래스를 재정의해야합니다.
11 protected Object _readMapAndClose(JsonParser p0, JavaType valueType)
12 protected Object _readValue(DeserializationConfig cfg, JsonParser p, JavaType valueType) -값 읽기 + 바인딩 작업의 실제 구현.
13 protected DefaultSerializerProvider _serializerProvider(SerializationConfig config)
14 protected Object _unwrapAndDeserialize(JsonParser p, DeserializationContext ctxt, DeserializationConfig config, JavaType rootType, JsonDeserializer<Object> deser)
15 protected void _verifySchemaType(FormatSchema schema)
16 void acceptJsonFormatVisitor(Class<?> type, JsonFormatVisitorWrapper visitor) -지정된 방문자를 사용하여 특정 유형에 대한 방문 유형 계층 구조를 지정하는 방법.
17 void acceptJsonFormatVisitor(JavaType type, JsonFormatVisitorWrapper visitor) -지정된 방문자를 사용하여 특정 유형에 대한 방문 유형 계층 구조를 지정하는 방법.
18 ObjectMapper addHandler(DeserializationProblemHandler h) -Deserialization 중 특정 문제를 처리하는 데 사용할 지정된 DeserializationProblemHandler를 추가하는 방법입니다.
19 ObjectMapper addMixIn(Class<?> target, Class<?> mixinSource) -지정된 클래스 또는 인터페이스를 보강하는 데 사용할 믹스 인 주석을 추가하는 데 사용하는 방법입니다.
20 boolean canDeserialize(JavaType type) -매퍼가 주어진 유형의 Object를 역 직렬화 할 수 있다고 생각하는지 확인하기 위해 호출 할 수있는 메소드입니다.
21 boolean canDeserialize(JavaType type, AtomicReference<Throwable> cause) -canDeserialize (JavaType)와 유사하지만 serializer를 구성하려고 할 때 던져진 실제 Throwable을 반환 할 수있는 메서드 : 실제 문제가 무엇인지 파악하는 데 유용 할 수 있습니다.
22 boolean canSerialize(Class<?> type) -매퍼가 주어진 Class의 인스턴스를 직렬화 할 수 있다고 생각하는지 확인하기 위해 호출 할 수있는 메소드.
23 boolean canSerialize(Class<?> type, AtomicReference<Throwable> cause) -canSerialize (Class)와 비슷하지만 serializer를 구성하려고 할 때 던져진 실제 Throwable을 반환 할 수있는 메서드 : 실제 문제가 무엇인지 알아내는 데 유용 할 수 있습니다.
24 ObjectMapper clearProblemHandlers() -이 매퍼에서 등록 된 모든 DeserializationProblemHandlers 인스턴스를 제거하는 방법입니다.
25 MutableConfigOverride configOverride(Classlt;?> type) -주어진 유형의 속성에 적용되는 유형별 재정의를 추가하거나 변경하는 데 필요한 특정 유형에 대한 변경 가능한 구성 재정의 개체를 가져 오는 접근 자입니다.
26 ObjectMapper configure(DeserializationFeature f, boolean state) -이 객체 매퍼에 대한 deserialization 기능의 on / off 상태를 변경하는 방법.
27 ObjectMapper configure(JsonGenerator.Feature f, boolean state) -이 오브젝트 매퍼가 생성하는 생성기 인스턴스에 대한 JsonGenerator 기능의 on / off 상태를 변경하는 방법.
28 ObjectMapper configure(JsonParser.Feature f, boolean state) -이 객체 매퍼가 생성하는 파서 인스턴스에 대해 지정된 JsonParser.Features의 상태를 변경하는 방법입니다.
29 ObjectMapper configure(MapperFeature f, boolean state) -이 매퍼 인스턴스에 대한 on / off 매퍼 기능의 상태를 변경하는 방법입니다.
30 ObjectMapper configure(SerializationFeature f, boolean state) -이 객체 매퍼에 대한 on / off 직렬화 기능의 상태를 변경하는 방법입니다.
31 JavaType constructType(Type t) -주어진 유형 (일반적으로 java.lang.Class)에서 명시 적 컨텍스트없이 JavaType을 구성하는 편리한 메소드입니다.
32 <T> T convertValue(Object fromValue, Class<T> toValueType) -변환이 필요한 경우 주어진 값에서 주어진 값 유형의 인스턴스로 2 단계 변환을 수행하는 편리한 방법입니다.
33 <T> T convertValue(Object fromValue, JavaType toValueType) -convertValue (Object, Class) 참조
34 <T> T convertValue(Object fromValue, TypeReference<?> toValueTypeRef) -convertValue (Object, Class) 참조
35 ObjectMapper copy() -이 인스턴스와 초기 구성이 동일한 새 ObjectMapper 인스턴스를 만드는 방법입니다.
36 ArrayNode createArrayNode() -참고 : 기본 ObjectCodec 추상화는 구체적인 노드 유형을 참조 할 수 없으므로 반환 유형은 공변입니다 (코어 패키지의 일부인 반면 impls는 매퍼 패키지의 일부 임).
37 ObjectNode createObjectNode() -참고 : 기본 ObjectCodec 추상화는 구체적인 노드 유형을 참조 할 수 없으므로 반환 유형은 공변입니다 (코어 패키지의 일부인 반면 impls는 매퍼 패키지의 일부 임).
38 protected ClassIntrospector defaultClassIntrospector() -사용할 기본 ClassIntrospector를 구성하는 데 사용되는 재정의 가능한 도우미 메서드입니다.
39 ObjectMapper disable(DeserializationFeature feature) -지정된 DeserializationConfig 기능을 활성화하는 방법입니다.
40 ObjectMapper disable(DeserializationFeature first, DeserializationFeature... f) -지정된 DeserializationConfig 기능을 활성화하는 방법입니다.
41 ObjectMapper disable(JsonGenerator.Feature... features) -이 객체 매퍼가 생성하는 파서 인스턴스에 대해 지정된 JsonGenerator.Features를 비활성화하는 메서드입니다.
42 ObjectMapper disable(JsonParser.Feature... features) -이 객체 매퍼가 생성하는 파서 인스턴스에 대해 지정된 JsonParser.Features를 비활성화하는 메서드입니다.
43 ObjectMapper disable(MapperFeature... f) -지정된 DeserializationConfig 기능을 활성화하는 방법입니다.
44 ObjectMapper disable(SerializationFeature f) -지정된 DeserializationConfig 기능을 활성화하는 방법입니다.
45 ObjectMapper disable(SerializationFeature first, SerializationFeature... f) -지정된 DeserializationConfig 기능을 활성화하는 방법입니다.
46 ObjectMapper disableDefaultTyping()-유형 정보의 자동 포함을 비활성화하는 방법 그렇다면 명시 적으로 주석이 추가 된 유형 (JsonTypeInfo가있는 유형) 만 추가로 포함 된 유형 정보를 갖게됩니다.
47 ObjectMapper enable(DeserializationFeature feature) -지정된 DeserializationConfig 기능을 활성화하는 방법입니다.
48 ObjectMapper enable(DeserializationFeature first, DeserializationFeature... f) -지정된 DeserializationConfig 기능을 활성화하는 방법입니다.
49 ObjectMapper enable(JsonGenerator.Feature... features) -이 객체 매퍼가 생성하는 파서 인스턴스에 대해 지정된 JsonGenerator.Features를 활성화하는 방법입니다.
50 ObjectMapper enable(JsonParser.Feature... features) -이 객체 매퍼가 생성하는 파서 인스턴스에 대해 지정된 JsonParser.Features를 활성화하는 방법입니다.
51 ObjectMapper enable(MapperFeature... f) -지정된 MapperConfig 기능을 활성화하는 방법.
52 ObjectMapper enable(SerializationFeature f) -지정된 DeserializationConfig 기능을 활성화하는 방법입니다.
53 ObjectMapper enable(SerializationFeature first, SerializationFeature... f) -지정된 DeserializationConfig 기능을 활성화하는 방법입니다.
54 ObjectMapper enableDefaultTyping() -통화에 해당하는 편리한 방법
55 ObjectMapper enableDefaultTyping(ObjectMapper.DefaultTyping dti) -통화에 해당하는 편리한 방법
56 ObjectMapper enableDefaultTyping(ObjectMapper.DefaultTyping applicability, JsonTypeInfo.As includeAs) -유형 정보의 자동 포함을 활성화하는 방법으로, 다형성 유형의 적절한 역 직렬화에 필요합니다 (유형에 JsonTypeInfo 주석이 추가되지 않은 경우).
57 ObjectMapper enableDefaultTypingAsProperty(ObjectMapper.DefaultTyping applicability, String propertyName) -유형 정보의 자동 포함을 활성화하는 방법-다형성 유형의 적절한 역 직렬화에 필요 (유형이 JsonTypeInfo로 주석이 달린 경우 제외)- "As.PROPERTY"포함 메커니즘 및 포함에 사용할 지정된 속성 이름 사용 (기본값은 "@ class "는 기본 유형 정보가 항상 유형 식별자로 클래스 이름을 사용하므로)
58 ObjectMapper findAndRegisterModules() -기능적으로 동일한 편의 메소드 : mapper.registerModules (mapper.findModules ());
59 Class<?> findMixInClassFor(Class<?> cls)
60 static List<Module> findModules() -모듈에서 제공하는 SPI와 함께 JDK ServiceLoader 기능을 사용하여 사용 가능한 메서드를 찾는 방법입니다.
61 static List<Module> findModules(ClassLoader classLoader) -모듈에서 제공하는 SPI와 함께 JDK ServiceLoader 기능을 사용하여 사용 가능한 메서드를 찾는 방법입니다.
62 DateFormat getDateFormat()
63 DeserializationConfig getDeserializationConfig() -deserialization에 대한 구성 설정을 정의하는 공유 기본 DeserializationConfig 개체를 반환하는 메서드입니다.
64 DeserializationContext getDeserializationContext() -현재 DeserializationContext를 가져 오는 방법입니다.
65 JsonFactory getFactory() -JsonParsers 및 / 또는 JsonGenerator를 구성해야하는 경우이 매퍼가 사용하는 JsonFactory를 확보하는 데 사용할 수있는 메소드입니다.
66 InjectableValues getInjectableValues()
67 JsonFactory getJsonFactory()-더 이상 사용되지 않습니다. 2.1 이후 : 대신 getFactory () 사용
68 JsonNodeFactory getNodeFactory() -Tree에 대한 루트 JsonNode 인스턴스를 직접 구성 할 때이 매퍼가 사용할 JsonNodeFactory를 확보하는 데 사용할 수있는 메소드입니다.
69 PropertyNamingStrategy getPropertyNamingStrategy()
70 SerializationConfig getSerializationConfig() -직렬화에 대한 구성 설정을 정의하는 공유 기본 SerializationConfig 개체를 반환하는 메서드입니다.
71 SerializerFactory getSerializerFactory() -현재 SerializerFactory를 가져 오는 방법.
72 SerializerProvider getSerializerProvider() -DefaultSerializerProvider.createInstance (com.fasterxml.jackson.databind.SerializationConfig, com.fasterxml.jackson.databind.ser.SerializerFactory)를 호출하여 인스턴스가 생성되는 "blueprint"(또는 팩토리) 인스턴스의 접근 자입니다.
73 SerializerProvider getSerializerProviderInstance() -serializer에 액세스하는 데 사용할 수있는 SerializerProvider 인스턴스를 구성하고 반환하는 접근 자입니다.
74 SubtypeResolver getSubtypeResolver() -사용중인 서브 타입 리졸버에 접근하는 방법.
75 TypeFactory getTypeFactory() -현재 구성된 TypeFactory 인스턴스를 얻기위한 접근 자.
76 VisibilityChecker<?> getVisibilityChecker()-현재 구성된 가시성 검사기에 액세스하는 방법; 지정된 속성 요소 (메서드, 필드, 생성자)를 자동 감지 할 수 있는지 여부를 결정하는 데 사용되는 객체입니다.
77 boolean isEnabled(DeserializationFeature f) -주어진 deserialization 관련 기능이 활성화되어 있는지 확인하는 방법입니다.
78 boolean isEnabled(JsonFactory.Feature f) -다음과 같은 편의 방법 :
79 boolean isEnabled(JsonGenerator.Feature f)
80 boolean isEnabled(JsonParser.Feature f)
81 boolean isEnabled(MapperFeature f) -주어진 MapperFeature가 활성화되어 있는지 확인하는 방법입니다.
82 boolean isEnabled(SerializationFeature f) -주어진 직렬화 관련 기능이 활성화되어 있는지 확인하는 방법입니다.
83 int mixInCount()
84 ObjectReader reader() -기본 설정으로 ObjectReader를 구성하는 공장 방법.
85 ObjectReader reader(Base64Variant defaultBase64) -Base64로 인코딩 된 바이너리 데이터에 대해 지정된 Base64 인코딩 변형을 사용할 ObjectReader를 구성하는 팩토리 방법입니다.
86 ObjectReader reader(Class<?> type)-더 이상 사용되지 않습니다. 2.5부터 대신 readerFor (Class) 사용
87 ObjectReader reader(ContextAttributes attrs) -지정된 기본 속성을 사용할 ObjectReader를 구성하는 팩토리 메소드입니다.
88 ObjectReader reader(DeserializationFeature feature) -지정된 기능이 활성화 된 ObjectReader를 구성하는 팩토리 방법 (이 매퍼 인스턴스에있는 설정과 비교).
89 ObjectReader reader(DeserializationFeature first, DeserializationFeature... other) -지정된 기능이 활성화 된 ObjectReader를 생성하는 팩토리 방법 (이 매퍼 인스턴스에있는 설정과 비교).
90 ObjectReader reader(FormatSchema schema) -콘텐츠 읽기에 사용되는 JsonParser에 특정 스키마 객체를 전달할 ObjectReader를 구성하는 팩토리 메소드입니다.
91 ObjectReader reader(InjectableValues injectableValues) -지정된 주입 가능 값을 사용할 ObjectReader를 구성하는 팩토리 메서드입니다.
92 ObjectReader reader(JavaType type)-더 이상 사용되지 않습니다. 2.5부터 대신 readerFor (JavaType) 사용
93 ObjectReader reader(JsonNodeFactory f) -JSON 트리를 구성하기 위해 지정된 JsonNodeFactory를 사용할 ObjectReader를 구성하는 팩토리 메소드입니다.
94 ObjectReader reader(TypeReference<?> type)-더 이상 사용되지 않습니다. 2.5부터 대신 readerFor (TypeReference) 사용
95 ObjectReader readerFor(Class<?> type) -지정된 유형의 인스턴스를 읽거나 업데이트 할 ObjectReader를 구성하는 팩토리 메소드
96 ObjectReader readerFor(JavaType type) -지정된 유형의 인스턴스를 읽거나 업데이트 할 ObjectReader를 구성하는 팩토리 메소드
97 ObjectReader readerFor(TypeReference<?> type) -지정된 유형의 인스턴스를 읽거나 업데이트 할 ObjectReader를 구성하는 팩토리 메소드
98 ObjectReader readerForUpdating(Object valueToUpdate) -JSON 데이터로 주어진 Object (일반적으로 Bean이지만 Collection 또는 Map 일 수 있지만 배열이 아님)를 업데이트 할 ObjectReader를 구성하는 팩토리 메소드입니다.
99 ObjectReader readerWithView(Class<?> view) -지정된 JSON View (필터)를 사용하여 개체를 deserialize하는 ObjectReader를 구성하는 팩토리 메서드입니다.
100 JsonNode readTree(byte[] content) -JsonNode 인스턴스 집합을 사용하여 표현 된 트리로 JSON 콘텐츠를 역 직렬화하는 방법.
101 JsonNode readTree(File file) -JsonNode 인스턴스 집합을 사용하여 표현 된 트리로 JSON 콘텐츠를 역 직렬화하는 방법.
102 JsonNode readTree(InputStream in) -JsonNode 인스턴스 집합을 사용하여 표현 된 트리로 JSON 콘텐츠를 역 직렬화하는 방법.
103 <T extends TreeNode> T readTree(JsonParser p) -JsonNode 인스턴스 집합을 사용하여 표현 된 트리로 JSON 콘텐츠를 역 직렬화하는 방법.
104 JsonNode readTree(Reader r) -JsonNode 인스턴스 집합을 사용하여 표현 된 트리로 JSON 콘텐츠를 역 직렬화하는 방법.
105 JsonNode readTree(String content) -JsonNode 인스턴스 집합을 사용하여 표현 된 트리로 JSON 콘텐츠를 역 직렬화하는 방법.
106 JsonNode readTree(URL source) -JsonNode 인스턴스 집합을 사용하여 표현 된 트리로 JSON 콘텐츠를 역 직렬화하는 방법.
107 <T> T readValue(byte[] src, Class<T> valueType)
108 <T> T readValue(byte[] src, int offset, int len, Class<T> valueType)
109 <T> T readValue(byte[] src, int offset, int len, JavaType valueType)
110 <T> T readValue(byte[] src, int offset, int len, TypeReference valueTypeRef)
111 <T> T readValue(byte[] src, JavaType valueType)
112 <T> T readValue(byte[] src, TypeReference valueTypeRef)
113 <T> T readValue(DataInput src, Class<T> valueType)
114 <T> T readValue(DataInput src, JavaType valueType)
115 <T> T readValue(File src, Class<T> valueType) -주어진 파일에서 주어진 자바 유형으로 JSON 콘텐츠를 역 직렬화하는 방법.
116 <T> T readValue(File src, JavaType valueType) -주어진 파일에서 주어진 자바 유형으로 JSON 콘텐츠를 역 직렬화하는 방법.
117 <T> T readValue(File src, TypeReference valueTypeRef) -주어진 파일에서 주어진 자바 유형으로 JSON 콘텐츠를 역 직렬화하는 방법.
118 <T> T readValue(InputStream src, Class<T> valueType)
119 <T> T readValue(InputStream src, JavaType valueType)
120 <T> T readValue(InputStream src, TypeReference valueTypeRef)
121 <T> T readValue(JsonParser p, Class<T> valueType) - Method to deserialize JSON content into a non-container type (it can be an array type, however): typically a bean, array or a wrapper type (like Boolean).
122 <T> T readValue(JsonParser p, JavaType valueType) -type-safe 오버로드 된 메서드, 기본적으로 readValue (JsonParser, Class)의 별칭입니다.
123 <T> T readValue(JsonParser p, ResolvedType valueType) -JSON 콘텐츠를 Java 유형으로 역 직렬화하는 방법으로 참조가 인수로 전달됩니다.
124 <T> T readValue(JsonParser p, TypeReference<?> valueTypeRef) -JSON 콘텐츠를 Java 유형으로 역 직렬화하는 방법으로 참조가 인수로 전달됩니다.
125 <T> T readValue(Reader src, Class<T> valueType) -
1 <T> T readValue(Reader src, JavaType valueType)
126 <T> T readValue(Reader src, TypeReference valueTypeRef)
127 <T> T readValue(String content, Class<T> valueType) -주어진 JSON 콘텐츠 문자열에서 JSON 콘텐츠를 역 직렬화하는 방법.
128 <T> T readValue(String content, JavaType valueType) -주어진 JSON 콘텐츠 문자열에서 JSON 콘텐츠를 역 직렬화하는 방법.
129 <T> T readValue(String content, TypeReference valueTypeRef) -주어진 JSON 콘텐츠 문자열에서 JSON 콘텐츠를 역 직렬화하는 방법.
130 <T> T readValue(URL src, Class<T> valueType) -주어진 자원에서 주어진 Java 유형으로 JSON 콘텐츠를 역 직렬화하는 방법.
131 <T> T readValue(URL src, JavaType valueType)
132 <T> T readValue(URL src, TypeReference valueTypeRef) -주어진 자원에서 주어진 Java 유형으로 JSON 콘텐츠를 역 직렬화하는 방법.
133 <T> MappingIterator<T> readValues(JsonParser p, Class<T> valueType) -다음과 같은 기능에 해당하는 편의 방법 :
134 <T> MappingIterator<T> readValues(JsonParser p, JavaType valueType) - Convenience method, equivalent in function to:
135 <T> MappingIterator<T> readValues(JsonParser p, ResolvedType valueType) - Convenience method, equivalent in function to:
136 <T> MappingIterator<T> readValues(JsonParser p, TypeReference<?>valueTypeRef) - Method for reading sequence of Objects from parser stream.
137 ObjectMapper registerModule(Module module) - Method for registering a module that can extend functionality provided by this mapper; for example, by adding providers for custom serializers and deserializers.
138 ObjectMapper registerModules(Iterable<Module> modules) - Convenience method for registering specified modules in order; functionally equivalent to:
139 ObjectMapper registerModules(Module... modules) - Convenience method for registering specified modules in order; functionally equivalent to:
140 void registerSubtypes(NamedType... types) - Method for registering specified class as a subtype, so that typename-based resolution can link supertypes to subtypes (as an alternative to using annotations).
141 ObjectMapper setAnnotationIntrospector(AnnotationIntrospector ai) - Method for setting AnnotationIntrospector used by this mapper instance for both serialization and deserialization.
142 ObjectMapper setAnnotationIntrospectors(AnnotationIntrospector serializerAI, AnnotationIntrospector deserializerAI) - Method for changing AnnotationIntrospector instances used by this mapper instance for serialization and deserialization, specifying them separately so that different introspection can be used for different aspects.
143 ObjectMapper setBase64Variant(Base64Variant v) - Method that will configure default Base64Variant that byte[] serializers and deserializers will use.
144 ObjectMapper setConfig(DeserializationConfig config) - Method that allows overriding of the underlying DeserializationConfig object.
145 ObjectMapper setConfig(SerializationConfig config) - Method that allows overriding of the underlying SerializationConfig object, which contains serialization-specific configuration settings.
146 ObjectMapper setDateFormat(DateFormat dateFormat) - Method for configuring the default DateFormat to use when serializing time values as Strings, and deserializing from JSON Strings.
147 ObjectMapper setDefaultPrettyPrinter(PrettyPrinter pp) - Method for specifying PrettyPrinter to use when "default pretty-printing" is enabled (by enabling SerializationFeature.INDENT_OUTPUT)
148 ObjectMapper setDefaultTyping(TypeResolverBuilder<?> typer) - Method for enabling automatic inclusion of type information, using specified handler object for determining which types this affects, as well as details of how information is embedded.
149 ObjectMapper setFilterProvider(FilterProvider filterProvider) - Method for configuring this mapper to use specified FilterProvider for mapping Filter Ids to actual filter instances.
150 Object setHandlerInstantiator(HandlerInstantiator hi) - Method for configuring HandlerInstantiator to use for creating instances of handlers (such as serializers, deserializers, type and type id resolvers), given a class.
151 ObjectMapper setInjectableValues(InjectableValues injectableValues) - Method for configuring InjectableValues which used to find values to inject.
152 ObjectMapper setLocale(Locale l) - Method for overriding default locale to use for formatting.
153 void setMixInAnnotations(Map<Class<?>,Class<?>> sourceMixins) - Deprecated. Since 2.5: replaced by a fluent form of the method; setMixIns(java.util.Map<java.lang.Class<?>, java.lang.Class<?>>).
154 ObjectMapper setMixInResolver(ClassIntrospector.MixInResolver resolver) - Method that can be called to specify given resolver for locating mix-in classes to use, overriding directly added mappings.
155 ObjectMapper setMixIns(Map<Class<?>,Class<?>> sourceMixins) - Method to use for defining mix-in annotations to use for augmenting annotations that processable (serializable / deserializable) classes have.
156 ObjectMapper setNodeFactory(JsonNodeFactory f) - Method for specifying JsonNodeFactory to use for constructing root level tree nodes (via method createObjectNode()
157 ObjectMapper setPropertyInclusion(JsonInclude.Value incl) - Method for setting default POJO property inclusion strategy for serialization.
158 ObjectMapper setPropertyNamingStrategy(PropertyNamingStrategy s) - Method for setting custom property naming strategy to use.
159 ObjectMapper setSerializationInclusion(JsonInclude.Include incl) - Convenience method, equivalent to calling:
160 ObjectMapper setSerializerFactory(SerializerFactory f) - Method for setting specific SerializerFactory to use for constructing (bean) serializers.
161 ObjectMapper setSerializerProvider(DefaultSerializerProvider p) - Method for setting "blueprint" SerializerProvider instance to use as the base for actual provider instances to use for handling caching of JsonSerializer instances.
162 ObjectMapper setSubtypeResolver(SubtypeResolver str) - Method for setting custom subtype resolver to use.
163 ObjectMapper setTimeZone(TimeZone tz) - Method for overriding default TimeZone to use for formatting.
164 ObjectMapper setTypeFactory(TypeFactory f) - Method that can be used to override TypeFactory instance used by this mapper.
165 ObjectMapper setVisibility(PropertyAccessor forMethod, JsonAutoDetect.Visibility visibility) - Convenience method that allows changing configuration for underlying VisibilityCheckers, to change details of what kinds of properties are auto-detected.
166 ObjectMapper setVisibility(VisibilityChecker<?> vc) - Method for setting currently configured VisibilityChecker, object used for determining whether given property element (method, field, constructor) can be auto-detected or not.
167 void setVisibilityChecker(VisibilityChecker<?> vc) - Deprecated. Since 2.6 use setVisibility(VisibilityChecker) instead.
168 JsonParser treeAsTokens(TreeNode n) - Method for constructing a JsonParser out of JSON tree representation.
169 <T> T treeToValue(TreeNode n, Class<T> valueType) - Convenience conversion method that will bind data given JSON tree contains into specific value (usually bean) type.
170 <T extends JsonNode> T valueToTree(Object fromValue) - Reverse of treeToValue(com.fasterxml.jackson.core.TreeNode, java.lang.Class<T>); given a value (usually bean), will construct equivalent JSON Tree representation.
171 Version version() - Method that will return version information stored in and read from jar that contains this class.
172 ObjectWriter writer() - Convenience method for constructing ObjectWriter with default settings.
173 ObjectWriter writer(Base64Variant defaultBase64) - Factory method for constructing ObjectWriter that will use specified Base64 encoding variant for Base64-encoded binary data.
174 ObjectWriter writer(CharacterEscapes escapes) -
175 ObjectWriter writer(ContextAttributes attrs) - Factory method for constructing ObjectWriter that will use specified default attributes.
176 ObjectWriter writer(DateFormat df) - Factory method for constructing ObjectWriter that will serialize objects using specified DateFormat; or, if null passed, using timestamp (64-bit number.
177 ObjectWriter writer(FilterProvider filterProvider) - Factory method for constructing ObjectWriter that will serialize objects using specified filter provider.
178 ObjectWriter writer(FormatSchema schema) - Factory method for constructing ObjectWriter that will pass specific schema object to JsonGenerator used for writing content.
179 ObjectWriter writer(PrettyPrinter pp) - Factory method for constructing ObjectWriter that will serialize objects using specified pretty printer for indentation (or if null, no pretty printer)
180 ObjectWriter writer(SerializationFeature feature) - Factory method for constructing ObjectWriter with specified feature enabled (compared to settings that this mapper instance has).
181 ObjectWriter writer(SerializationFeature first, SerializationFeature... other) - Factory method for constructing ObjectWriter with specified features enabled (compared to settings that this mapper instance has).
182 ObjectWriter writerFor(Class<?> rootType) - Factory method for constructing ObjectWriter that will serialize objects using specified root type, instead of actual runtime type of value.
183 ObjectWriter writerFor(JavaType rootType) - Factory method for constructing ObjectWriter that will serialize objects using specified root type, instead of actual runtime type of value.
184 ObjectWriter writerFor(TypeReference<?> rootType) - Factory method for constructing ObjectWriter that will serialize objects using specified root type, instead of actual runtime type of value.
185 ObjectWriter writerWithDefaultPrettyPrinter() - Factory method for constructing ObjectWriter that will serialize objects using the default pretty printer for indentation.
186 ObjectWriter writerWithType(Class<?> rootType) - Deprecated. Since 2.5, use writerFor(Class) instead.
187 ObjectWriter writerWithType(JavaType rootType) - Deprecated. Since 2.5, use writerFor(JavaType) instead.
188 ObjectWriter writerWithType(TypeReference<?> rootType) - Deprecated. Since 2.5, use writerFor(TypeReference) instead.
189 ObjectWriter writerWithView(Class<?> serializationView) - Factory method for constructing ObjectWriter that will serialize objects using specified JSON View (filter).
190 void writeTree(JsonGenerator jgen, JsonNode rootNode) - Method to serialize given JSON Tree, using generator provided.
191 void writeTree(JsonGenerator jgen, TreeNode rootNode)
192 void writeValue(DataOutput out, Object value)
193 void writeValue(File resultFile, Object value) - Method that can be used to serialize any Java value as JSON output, written to File provided.
194 void writeValue(JsonGenerator g, Object value) - Method that can be used to serialize any Java value as JSON output, using provided JsonGenerator.
195 void writeValue(OutputStream out, Object value) - Method that can be used to serialize any Java value as JSON output, using output stream provided (using encoding JsonEncoding.UTF8).
196 void writeValue(Writer w, Object value) - Method that can be used to serialize any Java value as JSON output, using Writer provided.
197 byte[] writeValueAsBytes(Object value) - Method that can be used to serialize any Java value as a byte array.
198 String writeValueAsString(Object value) - Method that can be used to serialize any Java value as a String.

Methods inherited

This class inherits methods from the following classes:

  • java.lang.Object

ObjectMapper Example

Create the following java program using any editor of your choice in say C:/> Jackson_WORKSPACE

File: JacksonTester.java

import java.io.IOException;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonTester {
   public static void main(String args[]){
   
      ObjectMapper mapper = new ObjectMapper();
      String jsonString = "{\"name\":\"Mahesh\", \"age\":21}";
      
      //map json to student
      try{
         Student student = mapper.readValue(jsonString, Student.class);
         
         System.out.println(student);
         
         jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(student);
         
         System.out.println(jsonString);
      }
      catch (JsonParseException e) { e.printStackTrace();}
      catch (JsonMappingException e) { e.printStackTrace(); }
      catch (IOException e) { e.printStackTrace(); }
   }
}

class Student {
   private String name;
   private int age;
   public Student(){}
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public int getAge() {
      return age;
   }
   public void setAge(int age) {
      this.age = age;
   }
   public String toString(){
      return "Student [ name: "+name+", age: "+ age+ " ]";
   }
}

Verify the result

Compile the classes using javac compiler as follows:

C:\Jackson_WORKSPACE>javac JacksonTester.java

Now run the jacksonTester to see the result:

C:\Jackson_WORKSPACE>java JacksonTester

Verify the Output

Student [ name: Mahesh, age: 21 ]
{
  "name" : "Mahesh",
  "age" : 21
}

Object Serialization

let's serialize a java object to a json file and then read that json file to get the object back. In this example, we've created Student class. We'll create a student.json file which will have a json representation of Student object.

Create a java class file named JacksonTester in C:\>Jackson_WORKSPACE.

File: JacksonTester.java

import java.io.File;
import java.io.IOException;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonTester {
   public static void main(String args[]){
      JacksonTester tester = new JacksonTester();
      try {
         Student student = new Student();
         student.setAge(10);
         student.setName("Mahesh");
         tester.writeJSON(student);

         Student student1 = tester.readJSON();
         System.out.println(student1);

      } catch (JsonParseException e) {
         e.printStackTrace();
      } catch (JsonMappingException e) {
         e.printStackTrace();
      } catch (IOException e) {
         e.printStackTrace();
      }
   }

   private void writeJSON(Student student) throws JsonGenerationException, JsonMappingException, IOException{
      ObjectMapper mapper = new ObjectMapper();	
      mapper.writeValue(new File("student.json"), student);
   }

   private Student readJSON() throws JsonParseException, JsonMappingException, IOException{
      ObjectMapper mapper = new ObjectMapper();
      Student student = mapper.readValue(new File("student.json"), Student.class);
      return student;
   }
}

class Student {
   private String name;
   private int age;
   public Student(){}
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public int getAge() {
      return age;
   }
   public void setAge(int age) {
      this.age = age;
   }
   public String toString(){
      return "Student [ name: "+name+", age: "+ age+ " ]";
   }	
}

Verify the result

Compile the classes using javac compiler as follows:

C:\Jackson_WORKSPACE>javac JacksonTester.java

Now run the jacksonTester to see the result:

C:\Jackson_WORKSPACE>java JacksonTester

Verify the Output

Student [ name: Mahesh, age: 10 ]

Data Binding

Data Binding API is used to convert JSON to and from POJO (Plain Old Java Object) using property accessor or using annotations. It is of two type.

  • Simple Data Binding - Converts JSON to and from Java Maps, Lists, Strings, Numbers, Booleans and null objects.

  • Full Data Binding - Converts JSON to and from any JAVA type.

ObjectMapper reads/writes JSON for both types of data bindings. Data Binding is most convenient way and is analogus to JAXB parer for XML.

Simple Data Binding

Simple data binding refers to mapping of JSON to JAVA Core data types. Following table illustrates the relationship between JSON types vs Java Types.

Sr. No. JSON Type Java Type
1 object LinkedHashMap<String,Object>
2 array ArrayList<Object>
3 string String
4 complete number Integer, Long or BigInteger
5 fractional number Double / BigDecimal
6 true | false Boolean
7 null null

Let's see simple data binding in action. Here we'll map JAVA basic types directly to JSON and vice versa.

Create a java class file named JacksonTester in C:\>Jackson_WORKSPACE.

File: JacksonTester.java

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonTester {
   public static void main(String args[]){
      JacksonTester tester = new JacksonTester();
         try {
            ObjectMapper mapper = new ObjectMapper();

            Map<String,Object> studentDataMap = new HashMap<String,Object>(); 
            int[] marks = {1,2,3};

            Student student = new Student();
            student.setAge(10);
            student.setName("Mahesh");
            // JAVA Object
            studentDataMap.put("student", student);
            // JAVA String
            studentDataMap.put("name", "Mahesh Kumar");   		
            // JAVA Boolean
            studentDataMap.put("verified", Boolean.FALSE);
            // Array
            studentDataMap.put("marks", marks);

            mapper.writeValue(new File("student.json"), studentDataMap);
            //result student.json
			//{ 
            //   "student":{"name":"Mahesh","age":10},
            //   "marks":[1,2,3],
            //   "verified":false,
            //   "name":"Mahesh Kumar"
            //}
            studentDataMap = mapper.readValue(new File("student.json"), Map.class);

            System.out.println(studentDataMap.get("student"));
            System.out.println(studentDataMap.get("name"));
            System.out.println(studentDataMap.get("verified"));
            System.out.println(studentDataMap.get("marks"));
      } catch (JsonParseException e) {
         e.printStackTrace();
      } catch (JsonMappingException e) {
         e.printStackTrace();
      } catch (IOException e) {
            e.printStackTrace();
      }
   }
}

class Student {
   private String name;
   private int age;
   public Student(){}
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public int getAge() {
      return age;
   }
   public void setAge(int age) {
      this.age = age;
   }
   public String toString(){
      return "Student [ name: "+name+", age: "+ age+ " ]";
   }	
}

Verify the result

Compile the classes using javac compiler as follows:

C:\Jackson_WORKSPACE>javac JacksonTester.java

Now run the jacksonTester to see the result:

C:\Jackson_WORKSPACE>java JacksonTester

Verify the Output

{name=Mahesh, age=10}
Mahesh Kumar
false
[1, 2, 3]

Full Data Binding

Full data binding refers to mapping of JSON to any JAVA Object.

//Create an ObjectMapper instance
ObjectMapper mapper = new ObjectMapper();	
//map JSON content to Student object
Student student = mapper.readValue(new File("student.json"), Student.class);
//map Student object to JSON content
mapper.writeValue(new File("student.json"), student);

Let's see simple data binding in action. Here we'll map JAVA Object directly to JSON and vice versa.

Create a java class file named JacksonTester in C:\>Jackson_WORKSPACE.

File: JacksonTester.java

import java.io.File;
import java.io.IOException;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonTester {
   public static void main(String args[]){
      JacksonTester tester = new JacksonTester();
      try {
         Student student = new Student();
         student.setAge(10);
         student.setName("Mahesh");
         tester.writeJSON(student);

         Student student1 = tester.readJSON();
         System.out.println(student1);

      } catch (JsonParseException e) {
         e.printStackTrace();
      } catch (JsonMappingException e) {
         e.printStackTrace();
      } catch (IOException e) {
         e.printStackTrace();
      }
   }

   private void writeJSON(Student student) throws JsonGenerationException, JsonMappingException, IOException{
      ObjectMapper mapper = new ObjectMapper();	
      mapper.writeValue(new File("student.json"), student);
   }

   private Student readJSON() throws JsonParseException, JsonMappingException, IOException{
      ObjectMapper mapper = new ObjectMapper();
      Student student = mapper.readValue(new File("student.json"), Student.class);
      return student;
   }
}

class Student {
   private String name;
   private int age;
   public Student(){}
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public int getAge() {
      return age;
   }
   public void setAge(int age) {
      this.age = age;
   }
   public String toString(){
      return "Student [ name: "+name+", age: "+ age+ " ]";
   }	
}

Verify the result

Compile the classes using javac compiler as follows:

C:\Jackson_WORKSPACE>javac JacksonTester.java

Now run the jacksonTester to see the result:

C:\Jackson_WORKSPACE>java JacksonTester

Verify the Output

Student [ name: Mahesh, age: 10 ]

Data Binding with Generics

In simple data binding, we've used Map class which use String as key and Object as a value object. Instead we can have concrete java object and type cast it to be used in JSON binding.

Consider the following example with a class UserData, a class to hold user specific data.

Create a java class file named JacksonTester in C:\>Jackson_WORKSPACE.

File: JacksonTester.java

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonTester {
   public static void main(String args[]){
      JacksonTester tester = new JacksonTester();
         try {
            ObjectMapper mapper = new ObjectMapper();

            Map<String, UserData> userDataMap = new HashMap<String, UserData>();
            UserData studentData = new UserData(); 
            int[] marks = {1,2,3};

            Student student = new Student();
            student.setAge(10);
            student.setName("Mahesh");
            // JAVA Object
            studentData.setStudent(student);
            // JAVA String
            studentData.setName("Mahesh Kumar");
            // JAVA Boolean
            studentData.setVerified(Boolean.FALSE);
            // Array
            studentData.setMarks(marks);
            TypeReference ref = new TypeReference<Map<String,UserData>>() { };
            userDataMap.put("studentData1", studentData);
            mapper.writeValue(new File("student.json"), userDataMap);
            //{
            //   "studentData1":
            //	 {
            //		"student":
            //		{
            //			"name":"Mahesh",
            //			"age":10
            //      },
            //      "name":"Mahesh Kumar",
            //      "verified":false,
            //      "marks":[1,2,3]
            //   }
            //}
            userDataMap = mapper.readValue(new File("student.json"), ref);

            System.out.println(userDataMap.get("studentData1").getStudent());
            System.out.println(userDataMap.get("studentData1").getName());
            System.out.println(userDataMap.get("studentData1").getVerified());
            System.out.println(Arrays.toString(userDataMap.get("studentData1").getMarks()));
      } catch (JsonParseException e) {
         e.printStackTrace();
      } catch (JsonMappingException e) {
         e.printStackTrace();
      } catch (IOException e) {
            e.printStackTrace();
      }
   }
}

class Student {
   private String name;
   private int age;
   public Student(){}
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public int getAge() {
      return age;
   }
   public void setAge(int age) {
      this.age = age;
   }
   public String toString(){
      return "Student [ name: "+name+", age: "+ age+ " ]";
   }	
}

class UserData {
   private Student student;
   private String name;
   private Boolean verified;
   private int[] marks;

   public UserData(){}

   public Student getStudent() {
      return student;
   }
   public void setStudent(Student student) {
      this.student = student;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public Boolean getVerified() {
      return verified;
   }
   public void setVerified(Boolean verified) {
      this.verified = verified;
   }
   public int[] getMarks() {
      return marks;
   }
   public void setMarks(int[] marks) {
      this.marks = marks;
   }		
}

Verify the result

Compile the classes using javac compiler as follows:

C:\Jackson_WORKSPACE>javac JacksonTester.java

Now run the jacksonTester to see the result:

C:\Jackson_WORKSPACE>java JacksonTester

Verify the Output

Student [ name: Mahesh, age: 10 ]
Mahesh Kumar
false
[1, 2, 3]

Tree Model

Tree Model prepares a in-memory tree representation of the JSON document. ObjectMapper build tree of JsonNode nodes. It is most flexible approach. It is analogus to DOM parser for XML.

Create Tree from JSON

ObjectMapper provides a pointer to root node of the tree after reading the JSON. Root Node can be used to traverse the complete tree. Consider the following code snippet to get the root node of a provided JSON String.

//Create an ObjectMapper instance
ObjectMapper mapper = new ObjectMapper();	
String jsonString = "{\"name\":\"Mahesh Kumar\", \"age\":21,\"verified\":false,\"marks\": [100,90,85]}";
//create tree from JSON
JsonNode rootNode = mapper.readTree(jsonString);

Traversing Tree Model

Get each node using relative path to the root node while traversing tree and process the data. Consider the following code snippet traversing the tree provided the root node.

JsonNode nameNode = rootNode.path("name");
System.out.println("Name: "+ nameNode.textValue());
 
JsonNode marksNode = rootNode.path("marks");
Iterator<JsonNode> iterator = marksNode.elements();

Example

Create a java class file named JacksonTester in C:\>Jackson_WORKSPACE.

File: JacksonTester.java

import java.io.IOException;
import java.util.Iterator;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonTester {
   public static void main(String args[]){

      try {
         ObjectMapper mapper = new ObjectMapper();
         String jsonString = "{\"name\":\"Mahesh Kumar\",  \"age\":21,\"verified\":false,\"marks\": [100,90,85]}";
         JsonNode rootNode = mapper.readTree(jsonString);

         JsonNode nameNode = rootNode.path("name");
         System.out.println("Name: "+ nameNode.textValue());

         JsonNode ageNode = rootNode.path("age");
         System.out.println("Age: " + ageNode.intValue());

         JsonNode verifiedNode = rootNode.path("verified");
         System.out.println("Verified: " + (verifiedNode.booleanValue() ? "Yes":"No"));

         JsonNode marksNode = rootNode.path("marks");
         Iterator<JsonNode> iterator = marksNode.elements();
         System.out.print("Marks: [ ");

         while (iterator.hasNext()) {
            JsonNode marks = iterator.next();
            System.out.print(marks.intValue() + " "); 
         }

         System.out.println("]");
      }
      catch (JsonParseException e) { e.printStackTrace(); }
      catch (JsonMappingException e) { e.printStackTrace(); }
      catch (IOException e) { e.printStackTrace(); }
   }
}

Verify the result

Compile the classes using javac compiler as follows:

C:\Jackson_WORKSPACE>javac JacksonTester.java

Now run the jacksonTester to see the result:

C:\Jackson_WORKSPACE>java JacksonTester

Verify the Output

Name: Mahesh Kumar
Age: 21
Verified: No
Marks: [ 100 90 85 ]

Tree to JSON

In this example, we've created a Tree using JsonNode and write it to a json file and read back.

Create a java class file named JacksonTester in C:\>Jackson_WORKSPACE.

File: JacksonTester.java

import java.io.IOException;
import java.util.Iterator;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonTester {
   public static void main(String args[]){

      try {
         ObjectMapper mapper = new ObjectMapper();
         String jsonString = "{\"name\":\"Mahesh Kumar\",  \"age\":21,\"verified\":false,\"marks\": [100,90,85]}";
         JsonNode rootNode = mapper.readTree(jsonString);

         JsonNode nameNode = rootNode.path("name");
         System.out.println("Name: "+ nameNode.textValue());

         JsonNode ageNode = rootNode.path("age");
         System.out.println("Age: " + ageNode.intValue());

         JsonNode verifiedNode = rootNode.path("verified");
         System.out.println("Verified: " + (verifiedNode.booleanValue() ? "Yes":"No"));

         JsonNode marksNode = rootNode.path("marks");
         Iterator<JsonNode> iterator = marksNode.elements();
         System.out.print("Marks: [ ");

         while (iterator.hasNext()) {
            JsonNode marks = iterator.next();
            System.out.print(marks.intValue() + " "); 
         }

         System.out.println("]");
      }
      catch (JsonParseException e) { e.printStackTrace(); }
      catch (JsonMappingException e) { e.printStackTrace(); }
      catch (IOException e) { e.printStackTrace(); }
   }
}

Verify the result

Compile the classes using javac compiler as follows:

C:\Jackson_WORKSPACE>javac JacksonTester.java

Now run the jacksonTester to see the result:

C:\Jackson_WORKSPACE>java JacksonTester

Verify the Output

Name: Mahesh Kumar
Age: 21
Verified: No
Marks: [ 100 90 85 ]

Tree to Java Objects

In this example, we've created a Tree using JsonNode and write it to a json file and read back tree and then convert it as a Student object.

Create a java class file named JacksonTester in C:\>Jackson_WORKSPACE.

File: JacksonTester.java

import java.io.File;
import java.io.IOException;
import java.util.Iterator;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

public class JacksonTester {
   public static void main(String args[]){
      JacksonTester tester = new JacksonTester();
      try {
         ObjectMapper mapper = new ObjectMapper();

         JsonNode rootNode = mapper.createObjectNode();
         JsonNode marksNode = mapper.createArrayNode();
         ((ArrayNode)marksNode).add(100);
         ((ArrayNode)marksNode).add(90);
         ((ArrayNode)marksNode).add(85);
         ((ObjectNode) rootNode).put("name", "Mahesh Kumar");
         ((ObjectNode) rootNode).put("age", 21);
         ((ObjectNode) rootNode).put("verified", false);
         ((ObjectNode) rootNode).put("marks",marksNode);

         mapper.writeValue(new File("student.json"), rootNode);

         rootNode = mapper.readTree(new File("student.json"));

         Student student = mapper.treeToValue(rootNode, Student.class);

         System.out.println("Name: "+ student.getName());
         System.out.println("Age: " + student.getAge());
         System.out.println("Verified: " + (student.isVerified() ? "Yes":"No"));
         System.out.println("Marks: "+Arrays.toString(student.getMarks()));
      } catch (JsonParseException e) {
         e.printStackTrace();
      } catch (JsonMappingException e) {
         e.printStackTrace();
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}
class Student {
   String name;
   int age;
   boolean verified;
   int[] marks;
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public int getAge() {
      return age;
   }
   public void setAge(int age) {
      this.age = age;
   }
   public boolean isVerified() {
      return verified;
   }
   public void setVerified(boolean verified) {
      this.verified = verified;
   }
   public int[] getMarks() {
      return marks;
   }
   public void setMarks(int[] marks) {
      this.marks = marks;
   }
}

Verify the result

Compile the classes using javac compiler as follows:

C:\Jackson_WORKSPACE>javac JacksonTester.java

Now run the jacksonTester to see the result:

C:\Jackson_WORKSPACE>java JacksonTester

Verify the Output

Name: Mahesh Kumar
Age: 21
Verified: No
Marks: [ 100 90 85 ]

Streaming API

Streaming API reads and writes JSON content as discrete events. JsonParser reads the data whereas JsonGenerator writes the data. It is most powerful approach among the three and is of lowest overhead and fastest in read/write opreations. It is Analogus to Stax parser for XML.

In this Article, we'll showcase using Jackson streaming APIs to read and write JSON data. Streaming API works with concept of token and every details of Json is to be handle carefuly. Following are two class which we'll use in the examples:

  • JsonGenerator - Write to JSON String.

  • JsonParser - Parse JSON String.

Writing JSON using JsonGenerator

Using JsonGenerator is pretty simple. First create the JsonGenerator using JsonFactory.createJsonGenerator() method and use it's write***() methods to write each json value.

JsonFactory jsonFactory = new JsonFactory();
JsonGenerator jsonGenerator = jsonFactory.createGenerator(new File(
   "student.json"), JsonEncoding.UTF8);
// {
jsonGenerator.writeStartObject();
// "name" : "Mahesh Kumar"
jsonGenerator.writeStringField("name", "Mahesh Kumar");

Let's see JsonGenerator in action. Create a java class file named JacksonTester in C:\>Jackson_WORKSPACE.

File: JacksonTester.java

import java.io.File;
import java.io.IOException;
import java.util.Map;

import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonTester {
   public static void main(String args[]){

      try {         
         JsonFactory jsonFactory = new JsonFactory();
         JsonGenerator jsonGenerator = jsonFactory.createGenerator(new File("student.json"), JsonEncoding.UTF8);

         jsonGenerator.writeStartObject();

         // "name" : "Mahesh Kumar"
         jsonGenerator.writeStringField("name", "Mahesh Kumar"); 

         // "age" : 21
         jsonGenerator.writeNumberField("age", 21);

         // "verified" : false
         jsonGenerator.writeBooleanField("verified", false);

         // "marks" : [100, 90, 85]
         jsonGenerator.writeFieldName("marks"); 

         // [
         jsonGenerator.writeStartArray(); 
         // 100, 90, 85
         jsonGenerator.writeNumber(100); 
         jsonGenerator.writeNumber(90); 
         jsonGenerator.writeNumber(85); 
         // ]

         jsonGenerator.writeEndArray(); 

         jsonGenerator.writeEndObject(); 
         jsonGenerator.close();        

         //result student.json
         //{ 
         //   "name":"Mahesh Kumar",
         //   "age":21,
         //   "verified":false,
         //   "marks":[100,90,85]
         //}

         ObjectMapper mapper = new ObjectMapper();
         Map<String,Object> dataMap = mapper.readValue(new File("student.json"), Map.class);

         System.out.println(dataMap.get("name"));
         System.out.println(dataMap.get("age"));
         System.out.println(dataMap.get("verified"));
         System.out.println(dataMap.get("marks"));
      } 
      catch (JsonParseException e) { e.printStackTrace(); } 
      catch (JsonMappingException e) { e.printStackTrace(); } 
      catch (IOException e) { e.printStackTrace(); }
   }
}

Verify the result

Compile the classes using javac compiler as follows:

C:\Jackson_WORKSPACE>javac JacksonTester.java

Now run the jacksonTester to see the result:

C:\Jackson_WORKSPACE>java JacksonTester

Verify the Output

Mahesh Kumar
21
false
[100, 90, 85]

Reading JSON using JsonParser

Using JsonParser is again pretty simple. First create the JsonParser using JsonFactory.createJsonParser() method and use it's nextToken() methods to read each json string as token. Check each token and process accordingly

JsonFactory jasonFactory = new JsonFactory();
JsonParser jsonParser = jasonFactory.createJsonParser(new File("student.json"));
while (jsonParser.nextToken() != JsonToken.END_OBJECT) {
   //get the current token
   String fieldname = jsonParser.getCurrentName();
   if ("name".equals(fieldname)) {
      //move to next token
      jsonParser.nextToken();
      System.out.println(jsonParser.getText());        	 
   }
}

Let's see JsonParser in action. Create a java class file named JacksonTester in C:\>Jackson_WORKSPACE.

File: JacksonTester.java

import java.io.File;
import java.io.IOException;
import java.util.Map;

import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonTester {
   public static void main(String args[]){
      JacksonTester tester = new JacksonTester();
      try {        	
         JsonFactory jsonFactory = new JsonFactory();

         JsonGenerator jsonGenerator = jsonFactory.createGenerator(new File(
            "student.json"), JsonEncoding.UTF8);
         jsonGenerator.writeStartObject();
         jsonGenerator.writeStringField("name", "Mahesh Kumar"); 
         jsonGenerator.writeNumberField("age", 21);
         jsonGenerator.writeBooleanField("verified", false); 
         jsonGenerator.writeFieldName("marks"); 
         jsonGenerator.writeStartArray(); // [
         jsonGenerator.writeNumber(100); 
         jsonGenerator.writeNumber(90); 
         jsonGenerator.writeNumber(85); 
         jsonGenerator.writeEndArray(); 
         jsonGenerator.writeEndObject(); 
         jsonGenerator.close();       	 

         //result student.json
         //{ 
         //   "name":"Mahesh Kumar",
         //   "age":21,
         //   "verified":false,
         //   "marks":[100,90,85]
         //}

         JsonParser jsonParser = jsonFactory.createParser(new File("student.json"));
         while (jsonParser.nextToken() != JsonToken.END_OBJECT) {
            //get the current token
            String fieldname = jsonParser.getCurrentName();
            if ("name".equals(fieldname)) {
               //move to next token
               jsonParser.nextToken();
               System.out.println(jsonParser.getText());        	 
            }
            if("age".equals(fieldname)){
               //move to next token
               jsonParser.nextToken();
               System.out.println(jsonParser.getNumberValue());        	 
            }
            if("verified".equals(fieldname)){
               //move to next token
               jsonParser.nextToken();
               System.out.println(jsonParser.getBooleanValue());        	 
            }
            if("marks".equals(fieldname)){
               //move to [ 
               jsonParser.nextToken();
               // loop till token equal to "]"
               while (jsonParser.nextToken() != JsonToken.END_ARRAY) {
                  System.out.println(jsonParser.getNumberValue()); 
               }
            }
         }
      } catch (JsonParseException e) {
         e.printStackTrace();
      } catch (JsonMappingException e) {
         e.printStackTrace();
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

Verify the result

Compile the classes using javac compiler as follows:

C:\Jackson_WORKSPACE>javac JacksonTester.java

Now run the jacksonTester to see the result:

C:\Jackson_WORKSPACE>java JacksonTester

Verify the Output

Mahesh Kumar
21
false
[100, 90, 85]

JsonGenerator Class

Introduction

JsonParser is the base class to define public API for reading Json content. Instances are created using factory methods of a JsonFactory instance.

Class declaration

Following is the declaration for org.codehaus.jackson.JsonParser class:

public abstract class JsonParser
   extends Object
      implements Closeable, Versioned

Nested Classes

S.N. Class & Description
1 static class JsonParser.Feature
Enumeration that defines all togglable features for parsers.
2 static class JsonParser.NumberType
Enumeration of possible "native" (optimal) types that can be used for numbers.

Fields

  • protected PrettyPrinter _cfgPrettyPrinter - Object that handles pretty-printing (usually additional white space to make results more human-readable) during output.

  • protected JsonToken _currToken - Last token retrieved via nextToken(), if any.

  • protected int _features - Bit flag composed of bits that indicate which JsonParser.Features are enabled.

  • protected JsonToken _lastClearedToken - Last cleared token, if any: that is, value that was in effect when clearCurrentToken() was called.

Constructors

S.N. Constructor & Description
1 protected JsonParser()
Default constructor
2 protected JsonParser(int features)

Class Methods

S.N. Method & Description
1 protected void _reportError(String msg) - Helper method used for constructing and throwing JsonGenerationException with given base message.
2 protected void _reportUnsupportedOperation()
3 protected void _throwInternal()
4 protected void _writeSimpleObject(Object value)- Helper method to try to call appropriate write method for given untyped Object.
5 boolean canOmitFields() - Introspection method to call to check whether it is ok to omit writing of Object fields or not.
6 boolean canUseSchema(FormatSchema schema) - Method that can be used to verify that given schema can be used with this generator (using setSchema(com.fasterxml.jackson.core.FormatSchema)).
7 boolean canWriteBinaryNatively() - Introspection method that may be called to see if the underlying data format supports "native" binary data; that is, an efficient output of binary content without encoding.
8 boolean canWriteObjectId() - Introspection method that may be called to see if the underlying data format supports some kind of Object Ids natively (many do not; for example, JSON doesn't).
9 boolean canWriteTypeId() - Introspection method that may be called to see if the underlying data format supports some kind of Type Ids natively (many do not; for example, JSON doesn't).
10 abstract void close() - Method called to close this generator, so that no more content can be written.
11 JsonGenerator configure(JsonGenerator.Feature f, boolean state) - Method for enabling or disabling specified feature: check JsonGenerator.Feature for list of available features.
12 void copyCurrentEvent(JsonParser jp) - Method for copying contents of the current event that the given parser instance points to.
13 void copyCurrentStructure(JsonParser jp) - Method for copying contents of the current event and following events that it encloses the given parser instance points to.
14 abstract JsonGenerator disable(JsonGenerator.Feature f) - Method for disabling specified features (check JsonGenerator.Feature for list of features)
15 abstract JsonGenerator enable(JsonGenerator.Feature f) - Method for enabling specified parser features: check JsonGenerator.Feature for list of available features.
16 abstract void flush() - Method called to flush any buffered content to the underlying target (output stream, writer), and to flush the target itself as well.
17 CharacterEscapes getCharacterEscapes() - Method for accessing custom escapes factory uses for JsonGenerators it creates.
18 abstract ObjectCodec getCodec() - Method for accessing the object used for writing Java object as Json content (using method writeObject(java.lang.Object)).
19 abstract int getFeatureMask() - Bulk access method for getting state of all standard JsonGenerator.Features.
20 int getHighestEscapedChar() - Accessor method for testing what is the highest unescaped character configured for this generator.
21 abstract JsonStreamContext getOutputContext()
22 Object getOutputTarget()- Method that can be used to get access to object that is used as target for generated output; this is usually either OutputStream or Writer, depending on what generator was constructed with.
23 PrettyPrinter getPrettyPrinter()- Accessor for checking whether this generator has a configured PrettyPrinter; returns it if so, null if none configured.
24 FormatSchema getSchema() - Method for accessing Schema that this parser uses, if any.
25 abstract boolean isClosed() - Method that can be called to determine whether this generator is closed or not.
26 abstract boolean isEnabled(JsonGenerator.Feature f) - Method for checking whether given feature is enabled.
27 JsonGenerator setCharacterEscapes(CharacterEscapes esc)-Method for defining custom escapes factory uses for JsonGenerators it creates.
28 abstract JsonGenerator setCodec(ObjectCodec oc)- Method that can be called to set or reset the object to use for writing Java objects as JsonContent (using method writeObject(java.lang.Object)).
29 abstract JsonGenerator setFeatureMask(int mask)-Bulk set method for (re)settting states of all standard JsonGenerator.Features
30 JsonGenerator setHighestNonEscapedChar(int charCode) - Method that can be called to request that generator escapes all character codes above specified code point (if positive value); or, to not escape any characters except for ones that must be escaped for the data format (if -1).
31 JsonGenerator setPrettyPrinter(PrettyPrinter pp) - Method for setting a custom pretty printer, which is usually used to add indentation for improved human readability.
32 JsonGenerator setRootValueSeparator(SerializableString sep) - Method that allows overriding String used for separating root-level JSON values (default is single space character)
33 void setSchema(FormatSchema schema) - Method to call to make this generator use specified schema.
33 abstract JsonGenerator useDefaultPrettyPrinter()- Convenience method for enabling pretty-printing using the default pretty printer (DefaultPrettyPrinter).
34 abstract Version version()- Accessor for finding out version of the bundle that provided this generator instance.
35 void writeArrayFieldStart(String fieldName)- Convenience method for outputting a field entry ("member") (that will contain a JSON Array value), and the START_ARRAY marker.
36 abstract void writeBinary(Base64Variant b64variant, byte[] data, int offset, int len)- Method that will output given chunk of binary data as base64 encoded, as a complete String value (surrounded by double quotes).
37 abstract int writeBinary(Base64Variant b64variant, InputStream data, int dataLength) - Method similar to writeBinary(Base64Variant,byte[],int,int), but where input is provided through a stream, allowing for incremental writes without holding the whole input in memory.
38 void writeBinary(byte[] data)- Similar to writeBinary(Base64Variant,byte[],int,int), but assumes default to using the Jackson default Base64 variant (which is Base64Variants.MIME_NO_LINEFEEDS).
39 void writeBinary(byte[] data, int offset, int len) - Similar to writeBinary(Base64Variant,byte[],int,int), but default to using the Jackson default Base64 variant (which is Base64Variants.MIME_NO_LINEFEEDS).
40 int writeBinary(InputStream data, int dataLength) - Similar to writeBinary(Base64Variant,InputStream,int), but assumes default to using the Jackson default Base64 variant (which is Base64Variants.MIME_NO_LINEFEEDS).
41 void writeBinaryField(String fieldName, byte[] data) - Convenience method for outputting a field entry ("member") that contains specified data in base64-encoded form.
42 abstract void writeBoolean(boolean state) - Method for outputting literal Json boolean value (one of Strings 'true' and 'false').
43 void writeBooleanField(String fieldName, boolean value) - Convenience method for outputting a field entry ("member") that has a boolean value.
44 abstract void writeEndArray() - Method for writing closing marker of a JSON Array value (character ']'; plus possible white space decoration if pretty-printing is enabled).
45 abstract void writeEndObject() - Method for writing closing marker of a JSON Object value (character '}'; plus possible white space decoration if pretty-printing is enabled).
46 abstract void writeFieldName(SerializableString name) - Method similar to writeFieldName(String), main difference being that it may perform better as some of processing (such as quoting of certain characters, or encoding into external encoding if supported by generator) can be done just once and reused for later calls.
47 abstract void writeFieldName(String name) - Method for writing a field name (JSON String surrounded by double quotes: syntactically identical to a JSON String value), possibly decorated by white space if pretty-printing is enabled.
48 abstract void writeNull() - Method for outputting literal Json null value.
49 void writeNullField(String fieldName) - Convenience method for outputting a field entry ("member") that has JSON literal value null.
50 abstract void writeNumber(BigDecimal dec) - Method for outputting indicate Json numeric value.
51 abstract void writeNumber(BigInteger v) - Method for outputting given value as Json number.
52 abstract void writeNumber(double d) - Method for outputting indicate Json numeric value.
53 abstract void writeNumber(float f) - Method for outputting indicate Json numeric value.
54 abstract void writeNumber(int v) - Method for outputting given value as Json number.
55 abstract void writeNumber(long v) - Method for outputting given value as Json number.
56 void writeNumber(short v) - Method for outputting given value as Json number.
57 abstract void writeNumber(String encodedValue) - Write method that can be used for custom numeric types that can not be (easily?) converted to "standard" Java number types.
58 void writeNumberField(String fieldName, BigDecimal value) - Convenience method for outputting a field entry ("member") that has the specified numeric value.
59 void writeNumberField(String fieldName, double value) - Convenience method for outputting a field entry ("member") that has the specified numeric value.
60 void writeNumberField(String fieldName, float value) - Convenience method for outputting a field entry ("member") that has the specified numeric value.
61 void writeNumberField(String fieldName, int value) - Convenience method for outputting a field entry ("member") that has the specified numeric value.
62 void writeNumberField(String fieldName, long value) - Convenience method for outputting a field entry ("member") that has the specified numeric value.
63 abstract void writeObject(Object pojo) - Method for writing given Java object (POJO) as Json.
64 void writeObjectField(String fieldName, Object pojo) - Convenience method for outputting a field entry ("member") that has contents of specific Java object as its value.
65 void writeObjectFieldStart(String fieldName) - Convenience method for outputting a field entry ("member") (that will contain a JSON Object value), and the START_OBJECT marker.
66 void writeObjectId(Object id) - Method that can be called to output so-called native Object Id.
67 void writeObjectRef(Object id) - Method that can be called to output references to native Object Ids.
68 void writeOmittedField(String fieldName) Method called to indicate that a property in this position was skipped.
69 abstract void writeRaw(char c) - Method that will force generator to copy input text verbatim with no modifications (including that no escaping is done and no separators are added even if context [array, object] would otherwise require such).
70 abstract void writeRaw(char[] text, int offset, int len) - Method that will force generator to copy input text verbatim with no modifications (including that no escaping is done and no separators are added even if context [array, object] would otherwise require such).
71 void writeRaw(SerializableString raw) - Method that will force generator to copy input text verbatim with no modifications (including that no escaping is done and no separators are added even if context [array, object] would otherwise require such).
72 abstract void writeRaw(String text) - Method that will force generator to copy input text verbatim with no modifications (including that no escaping is done and no separators are added even if context [array, object] would otherwise require such).
73 abstract void writeRaw(String text, int offset, int len) - Method that will force generator to copy input text verbatim with no modifications (including that no escaping is done and no separators are added even if context [array, object] would otherwise require such).
74 abstract void writeRawUTF8String(byte[] text, int offset, int length) - Method similar to writeString(String) but that takes as its input a UTF-8 encoded String that is to be output as-is, without additional escaping (type of which depends on data format; backslashes for JSON).
75 abstract void writeRawValue(char[] text, int offset, int len)
76 abstract void writeRawValue(String text)- Method that will force generator to copy input text verbatim without any modifications, but assuming it must constitute a single legal JSON value (number, string, boolean, null, Array or List).
77 abstract void writeRawValue(String text, int offset, int len)
78 abstract void writeStartArray()- Method for writing starting marker of a JSON Array value (character '['; plus possible white space decoration if pretty-printing is enabled).
79 abstract void writeStartObject() - Method for writing starting marker of a JSON Object value (character '{'; plus possible white space decoration if pretty-printing is enabled).
80 abstract void writeString(char[] text, int offset, int len) - Method for outputting a String value.
81 abstract void writeString(SerializableString text) - Method similar to writeString(String), but that takes SerializableString which can make this potentially more efficient to call as generator may be able to reuse quoted and/or encoded representation.
82 abstract void writeString(String text) - Method for outputting a String value.
83 void writeStringField(String fieldName, String value) - Convenience method for outputting a field entry ("member") that has a String value.
84 abstract void writeTree(TreeNode rootNode) - Method for writing given JSON tree (expressed as a tree where given JsonNode is the root) using this generator.
85 void writeTypeId(Object id) - Method that can be called to output so-called native Type Id.
86 abstract void writeUTF8String(byte[] text, int offset, int length) - Method similar to writeString(String) but that takes as its input a UTF-8 encoded String which has not been escaped using whatever escaping scheme data format requires (for JSON that is backslash-escaping for control characters and double-quotes; for other formats something else).

Methods inherited

This class inherits methods from the following classes:

  • java.lang.Object

JsonParser Class

Introduction

JsonParser is the base class to define public API for reading Json content. Instances are created using factory methods of a JsonFactory instance.

Class declaration

Following is the declaration for com.fasterxml.jackson.core.JsonParser class:

public abstract class JsonParser
   extends Object
      implements Closeable, Versioned

Nested Classes

S.N. Class & Description
1 static class JsonParser.Feature
Enumeration that defines all togglable features for parsers.
2 static class JsonParser.NumberType
Enumeration of possible "native" (optimal) types that can be used for numbers.

Fields

  • protected int _features - Bit flag composed of bits that indicate which JsonParser.Features are enabled.

Constructors

S.N. Constructor & Description
1 protected JsonParser()
Default constructor
2 protected JsonParser(int features)

Class Methods

S.N. Method & Description
1 protected JsonParseException _constructError(String msg) - Helper method for constructing JsonParseExceptions based on current state of the parser.
2 protected void _reportUnsupportedOperation() - Helper method to call for operations that are not supported by parser implementation.
3 boolean canReadObjectId() - Introspection method that may be called to see if the underlying data format supports some kind of Object Ids natively (many do not; for example, JSON doesn't).
4 boolean canReadTypeId() - Introspection method that may be called to see if the underlying data format supports some kind of Type Ids natively (many do not; for example, JSON doesn't).
5 boolean canUseSchema(FormatSchema schema) - Method that can be used to verify that given schema can be used with this parser (using setSchema(com.fasterxml.jackson.core.FormatSchema)).
6 abstract void clearCurrentToken() - Method called to "consume" the current token by effectively removing it so that hasCurrentToken() returns false, and getCurrentToken() null).
7 abstract void close() - Closes the parser so that no further iteration or data access can be made; will also close the underlying input source if parser either owns the input source, or feature JsonParser.Feature.AUTO_CLOSE_SOURCE is enabled.
8 JsonParser configure(JsonParser.Feature f, boolean state) - Method for enabling or disabling specified feature (check JsonParser.Feature for list of features)
9 JsonParser disable(JsonParser.Feature f) - Method for disabling specified feature (check JsonParser.Feature for list of features)
10 JsonParser enable(JsonParser.Feature f) - Method for enabling specified parser feature (check JsonParser.Feature for list of features)
11 abstract BigInteger getBigIntegerValue() - Numeric accessor that can be called when the current token is of type JsonToken.VALUE_NUMBER_INT and it can not be used as a Java long primitive type due to its magnitude.
12 byte[] getBinaryValue() - Convenience alternative to getBinaryValue(Base64Variant) that defaults to using Base64Variants.getDefaultVariant() as the default encoding.
13 abstract byte[] getBinaryValue(Base64Variant b64variant) - Method that can be used to read (and consume -- results may not be accessible using other methods after the call) base64-encoded binary data included in the current textual JSON value.
14 boolean getBooleanValue() - Convenience accessor that can be called when the current token is JsonToken.VALUE_TRUE or JsonToken.VALUE_FALSE.
15 byte getByteValue() - Numeric accessor that can be called when the current token is of type JsonToken.VALUE_NUMBER_INT and it can be expressed as a value of Java byte primitive type.
16 abstract ObjectCodec getCodec() - Accessor for ObjectCodec associated with this parser, if any.
17 abstract JsonLocation getCurrentLocation() - Method that returns location of the last processed character; usually for error reporting purposes.
18 abstract String getCurrentName() - Method that can be called to get the name associated with the current token: for JsonToken.FIELD_NAMEs it will be the same as what getText() returns; for field values it will be preceding field name; and for others (array values, root-level values) null.
19 abstract JsonToken getCurrentToken() - Accessor to find which token parser currently points to, if any; null will be returned if none.
20 abstract int getCurrentTokenId() - Method similar to getCurrentToken() but that returns an int instead of JsonToken (enum value).
21 abstract BigDecimal getDecimalValue() - Numeric accessor that can be called when the current token is of type JsonToken.VALUE_NUMBER_FLOAT or JsonToken.VALUE_NUMBER_INT.
22 abstract double getDoubleValue() - Numeric accessor that can be called when the current token is of type JsonToken.VALUE_NUMBER_FLOAT and it can be expressed as a Java double primitive type.
23 abstract Object getEmbeddedObject() - Accessor that can be called if (and only if) the current token is JsonToken.VALUE_EMBEDDED_OBJECT.
24 int getFeatureMask() - Bulk access method for getting state of all standard JsonParser.Features.
25 abstract float getFloatValue() - Numeric accessor that can be called when the current token is of type JsonToken.VALUE_NUMBER_FLOAT and it can be expressed as a Java float primitive type.
26 Object getInputSource() - Method that can be used to get access to object that is used to access input being parsed; this is usually either InputStream or Reader, depending on what parser was constructed with.
27 abstract int getIntValue() - Numeric accessor that can be called when the current token is of type JsonToken.VALUE_NUMBER_INT and it can be expressed as a value of Java int primitive type.
28 abstract JsonToken getLastClearedToken() - Method that can be called to get the last token that was cleared using clearCurrentToken().
29 abstract long getLongValue() - Numeric accessor that can be called when the current token is of type JsonToken.VALUE_NUMBER_INT and it can be expressed as a Java long primitive type.
30 abstract JsonParser.NumberType getNumberType() - If current token is of type JsonToken.VALUE_NUMBER_INT or JsonToken.VALUE_NUMBER_FLOAT, returns one of JsonParser.NumberType constants; otherwise returns null.
31 abstract Number getNumberValue() - Generic number value accessor method that will work for all kinds of numeric values.
32 Object getObjectId() - Method that can be called to check whether current token (one that was just read) has an associated Object id, and if so, return it.
33 abstract JsonStreamContext getParsingContext() - Method that can be used to access current parsing context reader is in.
34 FormatSchema getSchema() - Method for accessing Schema that this parser uses, if any.
35 short getShortValue() - Numeric accessor that can be called when the current token is of type JsonToken.VALUE_NUMBER_INT and it can be expressed as a value of Java short primitive type.
36 abstract String getText() - Method for accessing textual representation of the current token; if no current token (before first call to nextToken(), or after encountering end-of-input), returns null.
37 abstract char[] getTextCharacters() - Method similar to getText(), but that will return underlying (unmodifiable) character array that contains textual value, instead of constructing a String object to contain this information.
38 abstract int getTextLength() - Accessor used with getTextCharacters(), to know length of String stored in returned buffer.
39 abstract int getTextOffset() - Accessor used with getTextCharacters(), to know offset of the first text content character within buffer.
40 abstract JsonLocation getTokenLocation() - Method that return the starting location of the current token; that is, position of the first character from input that starts the current token.
41 Object getTypeId() - Method that can be called to check whether current token (one that was just read) has an associated type id, and if so, return it.
42 boolean getValueAsBoolean() - Method that will try to convert value of current token to a boolean.
43 boolean getValueAsBoolean(boolean defaultValue) - Method that will try to convert value of current token to a boolean.
44 double getValueAsDouble() - Method that will try to convert value of current token to a Java double.
45 double getValueAsDouble(double defaultValue) - Method that will try to convert value of current token to a Java double.
46 int getValueAsInt() - Method that will try to convert value of current token to a int.
47 int getValueAsInt(int defaultValue) - Method that will try to convert value of current token to a int.
48 long getValueAsLong() - Method that will try to convert value of current token to a long.
49 long getValueAsLong(long defaultValue) - Method that will try to convert value of current token to a long.
50 String getValueAsString() - Method that will try to convert value of current token to a String.
51 abstract String getValueAsString(String defaultValue) - Method that will try to convert value of current token to a String.
52 abstract boolean hasCurrentToken() - Method for checking whether parser currently points to a token (and data for that token is available).
53 abstract boolean hasTextCharacters() - Method that can be used to determine whether calling of getTextCharacters() would be the most efficient way to access textual content for the event parser currently points to.
54 abstract boolean isClosed() - Method that can be called to determine whether this parser is closed or not.
55 boolean isEnabled(JsonParser.Feature f) - Method for checking whether specified JsonParser.Feature is enabled.
56 boolean isExpectedStartArrayToken() - Specialized accessor that can be used to verify that the current token indicates start array (usually meaning that current token is JsonToken.START_ARRAY) when start array is expected.
57 Boolean nextBooleanValue() - Method that fetches next token (as if calling nextToken()) and if it is JsonToken.VALUE_TRUE or JsonToken.VALUE_FALSE returns matching Boolean value; otherwise return null.
58 boolean nextFieldName(SerializableString str) - Method that fetches next token (as if calling nextToken()) and verifies whether it is JsonToken.FIELD_NAME with specified name and returns result of that comparison.
59 int nextIntValue(int defaultValue) - Method that fetches next token (as if calling nextToken()) and if it is JsonToken.VALUE_NUMBER_INT returns 32-bit int value; otherwise returns specified default value It is functionally equivalent to:
60 long nextLongValue(long defaultValue) - Method that fetches next token (as if calling nextToken()) and if it is JsonToken.VALUE_NUMBER_INT returns 64-bit long value; otherwise returns specified default value It is functionally equivalent to:
61 String nextTextValue() - Method that fetches next token (as if calling nextToken()) and if it is JsonToken.VALUE_STRING returns contained String value; otherwise returns null.
62 abstract JsonToken nextToken() - Main iteration method, which will advance stream enough to determine type of the next token, if any.
63 abstract JsonToken nextValue() - Iteration method that will advance stream enough to determine type of the next token that is a value type (including JSON Array and Object start/end markers).
64 abstract void overrideCurrentName(String name) - Method that can be used to change what is considered to be the current (field) name.
65 int readBinaryValue(Base64Variant b64variant, OutputStream out) - Similar to readBinaryValue(OutputStream) but allows explicitly specifying base64 variant to use.
66 int readBinaryValue(OutputStream out) - Method that can be used as an alternative to getBigIntegerValue(), especially when value can be large.
67 <T> T readValueAs(Class<T> valueType) - Method to deserialize JSON content into a non-container type (it can be an array type, however): typically a bean, array or a wrapper type (like Boolean).
68 <T> T readValueAs(TypeReference<?> valueTypeRef)- Method to deserialize JSON content into a Java type, reference to which is passed as argument.
69 <T extends TreeNode> T readValueAsTree() - Method to deserialize JSON content into equivalent "tree model", represented by root TreeNode of resulting model.
70 <T> Iterator<T> readValuesAs(Class<T> valueType) - Method for reading sequence of Objects from parser stream, all with same specified value type.
71 <T> Iterator<T> readValuesAs(TypeReference<?> valueTypeRef)- Method for reading sequence of Objects from parser stream, all with same specified value type.
72 int releaseBuffered(OutputStream out) - Method that can be called to push back any content that has been read but not consumed by the parser.
73 int releaseBuffered(Writer w) - Method that can be called to push back any content that has been read but not consumed by the parser.
74 boolean requiresCustomCodec() - Method that can be called to determine if a custom ObjectCodec is needed for binding data parsed using JsonParser constructed by this factory (which typically also implies the same for serialization with JsonGenerator).
75 abstract void setCodec(ObjectCodec c) - Setter that allows defining ObjectCodec associated with this parser, if any.
76 JsonParser setFeatureMask(int mask) - Bulk set method for (re)settting states of all standard JsonParser.Features
77 void setSchema(FormatSchema schema) - Method to call to make this parser use specified schema.
78 abstract JsonParser skipChildren() - Method that will skip all child tokens of an array or object token that the parser currently points to, iff stream points to JsonToken.START_OBJECT or JsonToken.START_ARRAY.
79 abstract Version version() - Accessor for getting version of the core package, given a parser instance.

Methods inherited

This class inherits methods from the following classes:

  • java.lang.Object