Javatpoint Logo
Javatpoint Logo

ObjectMapper Class in Jackson

ObjectMapper is one of the most important class available in the Jackson library. It is used to read and write JSON data. It is responsible for reading data from or to POJO file and to and from a JSON Tree Model.

There are the following characteristics of ObjectMapper class:

  1. It supports advanced concepts such as Polymorphism and Object recognition.
  2. It is very customizable to work with different styles of JSON content.
  3. It works as a factory for the advance ObjectReader and ObjectWriter classes.

The ObjectMapper class is declared in the following way:

Nested Classes

The following table defines the classes that extend the ObjectMapper class or, can say, nested classes of ObjectMapper class.

Class Description
DefaultTypeResolverBuilder It is a customized TypeResolverBuilder class that is used to get the type resolver builders, which we can use with "default typing".
DefaultTyping In order to specify the kind of types, enumerations are used with the enableDefaultTyping() method.

Now, let's understand the fields, constructors, and methods of ObjectMapper class:

Fields of ObjectMapper Class

protected DefaultDeserializationContext _deserializationContext

It is a blueprint context object that is stored for allowing custom sub-classes.

protected DeserializationConfig _deserializationConfig

It is a configuration object which is used for defining the basic global settings for the de-serialization process.

protected JsonFactory jsonFactory

In order to create an instance of JsonParser and JsonGenerator, JsonFactory is used.

protected InjectableValues _injectableValues

It is a provider that is used for injecting the values in de-serialized POJOs.

protected ConfigOverrides _propertyOverrides

It is used to access the currently active per-type configuration overrides.

protected SimpleMixInResolver _mixIns

It is a mapping that is used to define a way of applying mix-in annotations. Mapping is done in the following way:

Key: Type to receive additional annotations.

Value: Type that has annotations to "mix in"

protected Set<Object> _registeredModuleTypes

It is a Set that defines the set of module types that have been registered.

protected SerializationConfig _serializationConfig

It is also a configuration object that is used to define the basic global settings for the serialization process.

protected ConcurrentHashMap<JavaType,JsonDeserializer<Object>> _rootDeserializers

It is a map that is used to keep track of root-level de-serializers. It is a main-level Map.

protected SerializerFactory _serializerFactory

It is a factory that is used to construct the serializers.

protected SubtypeResolver _subtypeResolver

It is used to register sub-types and to solve them for super/sub-types as needed.

protected TypeFactory _typeFactory

It is a factory that is used to create JavaType instances. They are required for allowing modules to add more custom type handling.

protected DefaultSerializerProvider _serializerProvider

It is an object that is responsible for managing the access to serializers used for serialization.

protected static BaseSettings DEFAULT_BASE

It is base settings that include defaults used for all ObjectMapper instances.

Constructors of the ObjectMapper Class

There are the following constructors of the ObjectMapper class:

Constructor Description
ObjectMapper() It is a default constructor used to construct an instance that uses default JsonFactory, SerializerProvider, and BeanSerializerFactory.
ObjectMapper(JsonFactory factory ) It is used to construct an instance that uses the given JsonFactory. The given JsonFactory is used to construct JsonParsers and/or JsonGenerators.
ObjectMapper(JsonFactory factory, SerializerProvider provider1, DeserializerProvider provider2) It is used to construct an instance that uses the given JsonFactory, SerializerProvider, and DeserializerProvider. The given JsonFactory is used to construct JsonParsers and/or JsonGenerators.
protected ObjectMapper(ObjectMapper mapper) It is a copy-constructor to support copy().

ObjectMapper Class Methods

The ObjectMapper class defines the following methods:

Method Return Type Description
_checkInvalidCopy(Class<?> exp) void It is used to check invalid copy.
_configAndWriteValue(JsonGenerator g, Object value) void It is used for configuring the generator when necessary and then performing the write functionality.
_convert(Object fromValue, JavaType toValueType) Object It is used to get the actual conversion implementation. Here, read and write methods are not used for the code.
_initForReading(JsonParser p) JsonToken It is used for ensuring whether the given parser is ready for reading content for data binding or not.
_findRootDeserializer(DeserializationContext ctxt, JavaType valueType) JsonDeserializer<Object> For the passed root-level value, if we want to locate the de-serializer, we use this method.
_newReader(DeserializationConfig config)
Similar method:
  1. _newReader(DeserializationConfig config, JavaType valueType, Object valueToUpdate, FormatSchema schema, InjectableValues injectableValues)
ObjectReader It is a factory method, i.e., used to get the ObjectReader instances of proper sub-type. In order to use this method, it is necessary that the sub-classes must override.
_newWriter(SerializationConfig config)
Similar methods:
  1. _newWriter(SerializationConfig config, FormatSchema schema)
  2. _newWriter(SerializationConfig config, JavaType rootType, PrettyPrinter pp)
ObjectWriter It is a factory method, i.e., used to get the ObjectWriter instances of proper sub-type. In order to use this method, it is necessary that the sub-classes must override.
_readValue(DeserializationConfig cfg, JsonParser p, JavaType valueType) Object It is used to get an object that defines value reading and binding operation.
_serializerProvider(SerializationConfig config) DefaultSerializerProvider It is an overridable helper method that is used to construct SerializerProvider.
acceptJsonFormatVisitor(Class<?> type, JsonFormatVisitorWrapper visitor)
Similar method:
  1. acceptJsonFormatVisitor(JavaType type, JsonFormatVisitorWrapper visitor)
void
void
If we want to visit the type hierarchy of a particular type with the specified visitor, we use this method.
addHandler(DeserializationProblemHandler h) ObjectMapper In order to handle specified problems during de-serialization, we use a specified DeserializationProblemHandler, and to add the handler, we use this method.
addMixIn(Class<?> target, Class<?> mixinSource) ObjectMapper In order to use mix-in annotation for specified augmenting class or interface, we use this method to add it.
canDeserialize(JavaType type) Boolean It is used to check whether the mapper can de-serialize an object of a specified type or not.
canDeserialize(JavaType type, AtomicReference<Throwable> cause) Boolean It is similar to the previous method. The only difference is that it can return the throwable that was thrown at the time of constructing the serializer. The throwable can be used to figure out the actual problem.
canSerialize(Class<?> type) Boolean It is used to check whether the mapper can serialize an object of a specified type or not.
canSerialize(Class<?> type, AtomicReference<Throwable> cause) Boolean It is similar to the previous method. The only difference is that it can return the throwable that was thrown at the time of constructing the serializer. The throwable can be used to figure out the actual problem.
clearProblemHandlers() ObjectMapper It is one of the methods that is used to remove all DeserializationProblemHandlers instances from the mapper which are registered.
configure(DeserializationFeature f, boolean state)
similar methods:
  1. configure(JsonGenerator.Feature f, boolean state)
  2. configure(JsonParser.Feature f, boolean state)
  3. configure(MapperFeature f, boolean state)
  4. configure(SerializationFeature f, boolean state)
ObjectMapper It is used to change the state of an on/off de-serialization, Json Generator, JsonParser, Mapper, or Serialization feature for the object mapper, generator instances, parser instances, mapper instance, or object mapper.
constructType(Type t) JavaType If we want to construct JavaType out of a given type without explicit context, we use this method.
convertValue(Object fromValue, Class toValueType)
Similar methods:
  1. convertValue(Object fromValue, JavaType toValueType)
T If we want to perform a two-step conversion of a given value into an instance of a given value type, we use the converValue() method.
createArrayNode() ArrayNode It is used to create ArrayNode.
defaultClassIntrospector() ClassIntrospector If we want to use the default ClassIntrospector, we use this Overridable helper method for constructing it.
disable(DeserializationFeature feature)
Similar methods:
  1. disable(DeserializationFeature first, DeserializationFeature... f)
  2. disable(JsonGenerator.Feature... features)
  3. disable(JsonParser.Feature... features)
  4. disable(MapperFeature... f)
  5. disable(SerializationFeature f)
  6. disable(SerializationFeature first, SerializationFeature... f)
ObjectMapper It is used to disable given DeserializationConfig, JsonGenerator.Features for parser instances, JsonParser.Features for parser instances of the object mapper.
disableDefaultTyping() ObjectMapper Many times, we need to disable the automatic inclusion of type information, and for this purpose, we use this method.
enable(DeserializationFeature feature)
  1. enable(DeserializationFeature first, DeserializationFeature... f)
  2. enable(JsonGenerator.Feature... features)
    enable(JsonParser.Feature... features)
  3. enable(MapperFeature... f)
  4. enable(SerializationFeature f)
  5. enable(SerializationFeature first, SerializationFeature... f)
ObjectMapper It is used to enable the given DeserializationConfig, JsonGenerator.Features for parser instances, JsonParser.Features for parser instances of the object mapper.
enableDefaultTyping()
Similar methods:
  1. enableDefaultTyping(ObjectMapper.DefaultTyping dti)
  2. enableDefaultTyping(ObjectMapper.DefaultTyping applicability, JsonTypeInfo.As includeAs)
  3. enableDefaultTypingAsProperty(ObjectMapper.DefaultTyping applicability, String propertyName)
ObjectMapper In order to use automatic inclusion of type information for de-serialization of polymorphic types., we use this method to enable it.
findAndRegisterModules() ObjectMapper It is similar to the mapper.registerModules(mapper.findModules()) method.
findModules()
Similar methods:
  1. findModules(ClassLoader classLoader)
List<Module> It is used to locate available methods. The method uses the JDK ServiceLoader facility with module-provided SPI.
getDateFormat() DateFormat It is used to get the format of the date.
getDeserializationConfig() DeserializationConfig It is used to get the shared default DeserializationConfig object. The returned object defines the configuration settings for de-serialization.
getDeserializationContext() DeserializationContext It is used to get the current DeserializationContext.
getFactory() JsonFactory If the mapper needs to construct a Json parser and generators, it needs json factory, and to get that, we use the getFactory() method.
getInjectableValues() InjectableValues It is used to get injectable values.
getJsonFactory() JsonFactory It is a deprecated method to get the Json factory.
getNodeFactory() JsonNodeFactory It is used to get the JsonNodeFactory that is used by the mapper at the time of directly constructing root JsonNode instances for Trees.
getPropertyNamingStrategy() PropertyNamingStrategy As the name implies, it is used to the naming strategy of the property.
getSerializationConfig() SerializationConfig It is used to get the shared default SerializationConfig object. The returned object defines the configuration settings for serialization.
getSerializerFactory() SerializerFactory It is used to get the current SerializerFactory.
getSerializerProvider() SerializerProvider It is an accessor for the factory, which is used to create instances by calling DefaultSerializerProvider.createInstance(SerializationConfig, SerializerFactory).
getSerializerProviderInstance() SerializerProvider It is an accessor that is used to construct and return an instance of the SerializerProvider, which we can use to access serializers.
getSubtypeResolver() SubtypeResolver It is used to access the subtype resolver in use.
getTypeFactory() TypeFactory It is an accessor that is used to get an instance of the currently configured TypeFactory.
getVisibilityChecker() VisibilityChecker<?> It is used to access the currently configured visibility checker.
isEnabled(DeserializationFeature f)
Similar Methods:
  1. isEnabled(JsonFactory.Feature f)
  2. isEnabled(JsonGenerator.Feature f)
  3. isEnabled(JsonParser.Feature f)
  4. isEnabled(MapperFeature f)
  5. isEnabled(SerializationFeature f)
Boolean The isEnable() method and its variations are used to check whether given deserialization-specific, JsonFactory, JsonGenerator, JsonParser, Mapper, or Serialization feature is enabled or not.
mixInCount() int It is used to get the count of mixIn.
reader()
Similar Methods:
  1. reader(Base64Variant defaultBase64)
  2. reader(Class<?> type)
  3. reader(ContextAttributes attrs)
  4. reader(DeserializationFeature feature)
  5. reader(DeserializationFeature first, DeserializationFeature... other)
  6. reader(FormatSchema schema)
  7. reader(InjectableValues injectableValues)
  8. reader(JavaType type)
  9. reader(JsonNodeFactory f)
  10. reader(TypeReference<?> type)
ObjectReader The reader() method and its variations are the factory methods that are used to construct an instance of ObjectReader. Based on the requirement, we can pass the Base64 encoding variant for Base64-encoded binary data, default attributes, features enabled, injectable values, JsonNodeFactory for constructing JSON trees.
readerFor(Class<?> type) ObjectReader It is a factory method that is used to construct ObjectReader, allowing read or update operations for instances of the specified type.
readerFor(JavaType type) ObjectReader It is a factory method that is used to construct ObjectReader, allowing read or update operations for instances of specified JavaType.
readerFor(TypeReference<?> type) ObjectReader It is a factory method that is used to construct ObjectReader, allowing read or update operations for instances of given TypeReference.
readerForUpdating(Object valueToUpdate) ObjectReader It is a factory method that is used to construct ObjectReader allowing update operations for the given object.
readerWithView(Class<?> view) ObjectReader It is a factory method that is used to construct ObjectReader, allowing
de-serialization of objects with given JSON View.
readTree(byte[] content)
  1. readTree(File file)
  2. readTree(InputStream in)
  3. readTree(JsonParser p)
  4. readTree(Reader r)
  5. readTree(String content)
  6. readTree(URL source)
JsonNode
OR
<T extends TreeNode> T
The readTree() and its variations are used to de-serialize the JSON content as a tree expressed using a set of JsonNode instances.
readValue(byte[] src, Class<T> valueType)
Similar Methods
  1. readValue(byte[] src, int offset, int len, JavaType valueType)
  2. readValue(byte[] src, int offset, int len, Class<T> valueType)
  3. readValue(byte[] src, JavaType valueType)
  4. readValue(DataInput src, Class<T> valueType)
  5. readValue(File src, Class<T> valueType)
  6. readValue(DataInput src, JavaType valueType)
  7. readValue(File src, JavaType valueType)
  8. readValue(File src, TypeReference valueTypeRef)
  9. readValue(InputStream src, JavaType valueType)
  10. readValue(byte[] src, TypeReference valueTypeRef)
  11. readValue(InputStream src, Class<T> valueType)
  12. readValue(InputStream src, TypeReference valueTypeRef)
  13. readValue(JsonParser p, JavaType valueType)
  14. readValue(JsonParser p, Class<T> valueType)
  15. readValue(JsonParser p, ResolvedType valueType)
  16. readValue(byte[] src, int offset, int len, TypeReference valueTypeRef)
  17. readValue(Reader src, TypeReference valueTypeRef)
  18. readValue(JsonParser p, TypeReference<?> valueTypeRef)
  19. readValue(Reader src, JavaType valueType)
  20. readValue(String content, TypeReference valueTypeRef)
  21. readValue(Reader src, Class<T> valueType)
  22. readValue(String content, Class<T> valueType)
  23. readValue(String content, JavaType valueType)
  24. readValue(URL src, TypeReference valueTypeRef)readValue(URL src, Class<T> valueType)
  25. readValue(URL src, JavaType valueType)
<T> T
OR
<T> MappingIterator<T>
The readValue() and its variations are used to de-serialize JSON content
  1. From the given file into a given Java type, into a non-container type, or into a Java type reference to which it is passed as an argument.
  2. From given JSON content into String.
  3. From given resource into given Java type.
Variations are used based on different requirements.
readValues(JsonParser p, Class<T> valueType)
Similar methods:
  1. readValues(JsonParser p, JavaType valueType)
  2. readValues(JsonParser p, ResolvedType valueType)
  3. readValues(JsonParser p, TypeReference<?>valueTypeRef)
<T> MappingIterator<T> The readValues() and its variations are used to read the sequence of Objects from the parser stream.
registerModule(Module module)
Similar methods:
  1. registerModules(Iterable<Module> modules)
  2. registerModules(Module... modules)
ObjectMapper The registerModule() and its variations are used to register a module having the capability to extend the functionality provided by the mapper.
registerSubtypes(NamedType... types) void It is used to register the given class as a subtype. By doing that, the type name-based resolution can link supertypes to subtypes.
setAnnotationIntrospector(AnnotationIntrospector ai) ObjectMapper It is used to set AnnotationIntrospector, which is used by the mapper instance for both serialization and de-serialization.
setAnnotationIntrospectors(AnnotationIntrospector serializerAI, AnnotationIntrospector deserializerAI) ObjectMapper It is used to change the instance of AnnotationIntrospector used by the current mapper instance for serialization and de-serialization.
setBase64Variant(Base64Variant v) ObjectMapper It is used to configure the default Base64Variant that will use by the byte[] serializers and de-serializers.
setConfig(DeserializationConfig config) ObjectMapper In order to perform the overriding of the underlying DeserializationConfig Object, we use this method.
setConfig(SerializationConfig config) ObjectMapper In order to perform the overriding of the underlying SerializationConfig Object having serialization-specific configuration settings, we use this method.
setDateFormat(DateFormat dateFormat) ObjectMapper It is used to configure the default DateFormat to use it at the time of serializing time values as Strings or de-serializing from JSON Strings.
setDefaultPrettyPrinter(PrettyPrinter pp) ObjectMapper It is used to specify the PrettyPrinter for using it when "default pretty-printing" is enabled.
setDefaultTyping(TypeResolverBuilder<?> typer) ObjectMapper It is used to enable the automatic inclusion of type information.
setHandlerInstantiator(HandlerInstantiator hi) Object It is used to configure HandlerInstantiator to use for creating instances of handlers.
setFilterProvider(FilterProvider filterProvider) ObjectMapper It is used to configure the current mapper to use specified FilterProvider for mapping Filter Ids to actual filter instances.
setInjectableValues(InjectableValues injectableValues) ObjectMapper It is used to configure InjectableValues which is used to find values to inject.
setLocale(Locale l) ObjectMapper It is used to override the default locale to use for formatting.
setMixInResolver(ClassIntrospector.MixInResolver resolver) ObjectMapper We use this method to specify the given resolver to locate mix-in classes to use, overriding directly added mappings.
setMixInAnnotations(Map<Class<?>,Class<?>> sourceMixins) void It is a depreciated method for defining mix-in annotation.
setNodeFactory(JsonNodeFactory f) ObjectMapper It is used to specify JsonNodeFactory to use for constructing root level tree nodes.
setMixIns(Map<Class<?>,Class<?>> sourceMixins) ObjectMapper It is used to define the mix-in annotations to use for augmenting annotations that processable classes have.
setPropertyInclusion(JsonInclude.Value incl) ObjectMapper It is used to set the default POJO property inclusion strategy for serialization.
setPropertyNamingStrategy(PropertyNamingStrategy s) ObjectMapper It is used to set the custom property naming strategy to use.
setSerializerFactory(SerializerFactory f) ObjectMapper It is used to set the specific SerializerFactory to use for constructing (bean) serializers.
setSerializerProvider(DefaultSerializerProvider p) ObjectMapper It is used to set the "blueprint" SerializerProvider instance for using it as the base to actual provider instances to use for handling caching of JsonSerializer instances.
setSubtypeResolver(SubtypeResolver str) ObjectMapper It is used to set the custom subtype resolver to use.
setTimeZone(TimeZone tz) ObjectMapper It is used to override the default TimeZone to use for formatting.
setTypeFactory(TypeFactory f) ObjectMapper It is used for overriding the TypeFactory instance, which is used by the current mapper.
setVisibility(PropertyAccessor forMethod, JsonAutoDetect.Visibility visibility)
  1. setVisibility(VisibilityChecker<?> vc)
  2. setVisibilityChecker(VisibilityChecker<?> vc)
ObjectMapper The setVisibility() and its variation are used to set the currently configured VisibilityChecker. The returned ObjectMapper instance is used to check whether the given property element can be auto-detected or not.
treeAsTokens(TreeNode n) JsonParser It is used to construct a JsonParser out of JSON tree representation.
treeToValue(TreeNode n, Class<T> valueType) <T> T It is used to bind the data given JSON tree contains into a specific value type.
version() Version It is used to get the version information stored in and read from the jar that contains this class.
writer()
  1. writer(Base64Variant defaultBase64)
  2. writer(CharacterEscapes escapes)
  3. writer(ContextAttributes attrs)
  4. writer(DateFormat df)
  5. writer(FilterProvider filterProvider)
  6. writer(FormatSchema schema)
  7. writer(PrettyPrinter pp)
  8. writer(SerializationFeature feature)
  9. writer(SerializationFeature first, SerializationFeature... other)
ObjectWriter The write() and its variations are used to construct ObjectWriter with default settings, given Base64 encoding variant for Base64-encoded binary data, character escaping details for output, default attributes, DateFormat, filter provider, schema object to JsonGenerator used for writing content, pretty printer for indentation, or feature enabled.
writerFor(Class<?> rootType) - ObjectWriter It is used to construct ObjectWriter for serializing the objects using a specified root type instead of the actual runtime type of value.
writerFor(JavaType rootType) ObjectWriter It is used to construct ObjectWriter for serializing the objects using a specified root type instead of the actual runtime type of value.
writerFor(TypeReference<?> rootType) ObjectWriter It is used to construct ObjectWriter for serializing the objects using a specified root type instead of the actual runtime type of value.
writerWithDefaultPrettyPrinter() ObjectWriter It is a factory method that is used to construct ObjectWriter for serializing the objects using the pretty default printer for indentation.
writerWithType(Class<?> rootType)
  1. writerWithType(Class<?> rootType)
  2. writerWithType(TypeReference<?> rootType)
ObjectWriter These methods are depreciated, and instead of them, we use the writerFor(TypeReference) method.
writerWithView(Class<?> serializationView) ObjectWriter It is a factory method that is used to construct ObjectWriter for serializing objects using specified JSON View.
writeTree(JsonGenerator jgen, JsonNode rootNode) void It is used for serializing the provided JSON Tree by using the given JsonGenerator.
writeValue(File resultFile, Object value) void It is used to serialize Java value as JSON output and write it to the given file.
writeValue(JsonGenerator g, Object value). void It is used to serialize Java values as JSON output by using the given JsonGenerator.
writeValue(OutputStream out, Object value) void It is used to serialize Java value as JSON output by using the given OutputStream.
writeValue(Writer w, Object value) void It is used to serialize Java values as JSON output by using the given Writer.
writeValueAsBytes(Object value) byte[] It is used for serializing Java values as a byte array.
writeValueAsString(Object value) String It is used for serializing Java values as a String.

JacksonExample.java

Output:

ObjectMapper Class in Jackson





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA