Class ObjectMapper
- All Implemented Interfaces:
Versioned,Serializable
- Direct Known Subclasses:
JsonMapper,XmlMapper
JsonNode), as well as
related functionality for performing conversions.
It is also highly customizable to work both with different styles of JSON
content, and to support more advanced Object concepts such as
polymorphism and Object identity.
ObjectMapper also acts as a factory for more advanced ObjectReader
and ObjectWriter classes.
Mapper (and ObjectReaders, ObjectWriters it constructs) will
use instances of JsonParser and JsonGenerator
for implementing actual reading/writing of JSON.
Note that although most read and write methods are exposed through this class,
some of the functionality is only exposed via ObjectReader and
ObjectWriter: specifically, reading/writing of longer sequences of
values is only available through ObjectReader.readValues(InputStream)
and ObjectWriter.writeValues(OutputStream).
Simplest usage is of form:
final ObjectMapper mapper = new ObjectMapper(); // can use static singleton, inject: just make sure to reuse!
MyValue value = new MyValue();
// ... and configure
File newState = new File("my-stuff.json");
mapper.writeValue(newState, value); // writes JSON serialization of MyValue instance
// or, read
MyValue older = mapper.readValue(new File("my-older-stuff.json"), MyValue.class);
// Or if you prefer JSON Tree representation:
JsonNode root = mapper.readTree(newState);
// and find values by, for example, using a JsonPointer expression:
int age = root.at("/personal/age").getValueAsInt();
The main conversion API is defined in ObjectCodec, so that
implementation details of this class need not be exposed to
streaming parser and generator classes. Usage via ObjectCodec is,
however, usually only for cases where dependency to ObjectMapper is
either not possible (from Streaming API), or undesireable (when only relying
on Streaming API).
Mapper instances are fully thread-safe provided that ALL configuration of the instance occurs before ANY read or write calls. If configuration of a mapper instance is modified after first usage, changes may or may not take effect, and configuration calls themselves may fail. If you need to use different configuration, you have two main possibilities:
- Construct and use
ObjectReaderfor reading,ObjectWriterfor writing. Both types are fully immutable and you can freely create new instances with different configuration using either factory methods ofObjectMapper, or readers/writers themselves. Construction of newObjectReaders andObjectWriters is a very light-weight operation so it is usually appropriate to create these on per-call basis, as needed, for configuring things like optional indentation of JSON. - If the specific kind of configurability is not available via
ObjectReaderandObjectWriter, you may need to use multipleObjectMapperinstead (for example: you cannot change mix-in annotations on-the-fly; or, set of custom (de)serializers). To help with this usage, you may want to use methodcopy()which creates a clone of the mapper with specific configuration, and allows configuration of the copied instance before it gets used. Note thatcopy()operation is as expensive as constructing a newObjectMapperinstance: if possible, you should still pool and reuse mappers if you intend to use them for multiple operations.
Note on caching: root-level deserializers are always cached, and accessed using full (generics-aware) type information. This is different from caching of referenced types, which is more limited and is done only for a subset of all deserializer types. The main reason for difference is that at root-level there is no incoming reference (and hence no referencing property, no referral information or annotations to produce differing deserializers), and that the performance impact greatest at root level (since it'll essentially cache the full graph of deserializers involved).
Notes on security: use of "default typing" feature (see enableDefaultTyping())
is a potential security risk, if used with untrusted content (content generated by
untrusted external parties). If so, you may want to construct a custom
TypeResolverBuilder implementation to limit possible types to instantiate,
(using setDefaultTyping(com.fasterxml.jackson.databind.jsontype.TypeResolverBuilder<?>)).
- See Also:
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic classCustomizedTypeResolverBuilderthat provides type resolver builders used with so-called "default typing" (seeactivateDefaultTyping(PolymorphicTypeValidator)for details).static enumEnumeration used withactivateDefaultTyping(PolymorphicTypeValidator)to specify what kind of types (classes) default typing should be used for. -
Constructor Summary
ConstructorsConstructorDescriptionDefault constructor, which will construct the defaultJsonFactoryas necessary, useSerializerProvideras itsSerializerProvider, andBeanSerializerFactoryas itsSerializerFactory.Constructs instance that uses specifiedJsonFactoryfor constructing necessaryJsonParsers and/orJsonGenerators.Constructs instance that uses specifiedJsonFactoryfor constructing necessaryJsonParsers and/orJsonGenerators, and uses given providers for accessing serializers and deserializers. -
Method Summary
Modifier and TypeMethodDescriptionvoidacceptJsonFormatVisitor(JavaType type, JsonFormatVisitorWrapper visitor) Method for visiting type hierarchy for given type, using specified visitor.voidacceptJsonFormatVisitor(Class<?> type, JsonFormatVisitorWrapper visitor) Method for visiting type hierarchy for given type, using specified visitor.Convenience method that is equivalent to callingactivateDefaultTyping(PolymorphicTypeValidator ptv, ObjectMapper.DefaultTyping applicability) Convenience method that is equivalent to callingactivateDefaultTyping(PolymorphicTypeValidator ptv, ObjectMapper.DefaultTyping applicability, JsonTypeInfo.As includeAs) Method for enabling automatic inclusion of type information ("Default Typing"), needed for proper deserialization of polymorphic types (unless types have been annotated withJsonTypeInfo).activateDefaultTypingAsProperty(PolymorphicTypeValidator ptv, ObjectMapper.DefaultTyping applicability, String propertyName) Method for enabling automatic inclusion of type information ("Default Typing") -- needed for proper deserialization of polymorphic types (unless types have been annotated withJsonTypeInfo) -- using "As.PROPERTY" inclusion mechanism and specified property name to use for inclusion (default being "@class" since default type information always uses class name as type identifier)Method for adding specifiedDeserializationProblemHandlerto be used for handling specific problems during deserialization.Method to use for adding mix-in annotations to use for augmenting specified class or interface.final voidaddMixInAnnotations(Class<?> target, Class<?> mixinSource) Deprecated.booleancanDeserialize(JavaType type) Method that can be called to check whether mapper thinks it could deserialize an Object of given type.booleancanDeserialize(JavaType type, AtomicReference<Throwable> cause) Method similar tocanDeserialize(JavaType)but that can return actualThrowablethat was thrown when trying to construct serializer: this may be useful in figuring out what the actual problem is.booleancanSerialize(Class<?> type) Method that can be called to check whether mapper thinks it could serialize an instance of given Class.booleancanSerialize(Class<?> type, AtomicReference<Throwable> cause) Method similar tocanSerialize(Class)but that can return actualThrowablethat was thrown when trying to construct serializer: this may be useful in figuring out what the actual problem is.Method for removing all registeredDeserializationProblemHandlers instances from this mapper.Accessor forMutableCoercionConfigthrough which default (fallback) coercion configurations can be changed.coercionConfigFor(LogicalType logicalType) Accessor forMutableCoercionConfigthrough which coercion configuration for specified logical target type can be set.coercionConfigFor(Class<?> physicalType) Accessor forMutableCoercionConfigthrough which coercion configuration for specified physical target type can be set.configOverride(Class<?> type) Accessor for getting a mutable configuration override object for given type, needed to add or change per-type overrides applied to properties of given type.configure(JsonGenerator.Feature f, boolean state) Method for changing state of an on/offJsonGeneratorfeature for generator instances this object mapper creates.configure(JsonParser.Feature f, boolean state) Method for changing state of specifiedJsonParser.Features for parser instances this object mapper creates.configure(DatatypeFeature f, boolean state) Method for changing state of an on/off datatype-specific feature for this object mapper.configure(DeserializationFeature f, boolean state) Method for changing state of an on/off deserialization feature for this object mapper.configure(MapperFeature f, boolean state) Deprecated.Since 2.13 useJsonMapper.builder().configure(...)configure(SerializationFeature f, boolean state) Method for changing state of an on/off serialization feature for this object mapper.constructType(TypeReference<?> typeRef) Convenience method for constructingJavaTypeout of given type reference.Convenience method for constructingJavaTypeout of given type (typicallyjava.lang.Class), but without explicit context.<T> TconvertValue(Object fromValue, TypeReference<T> toValueTypeRef) <T> TconvertValue(Object fromValue, JavaType toValueType) <T> TconvertValue(Object fromValue, Class<T> toValueType) Convenience method for doing two-step conversion from given value, into instance of given value type, by writing value into temporary buffer and reading from the buffer into specified target type.copy()Method for creating a newObjectMapperinstance that has same initial configuration as this instance.copyWith(JsonFactory factory) Method for creating a newObjectMapper.Note: return type is co-variant, as basic ObjectCodec abstraction cannot refer to concrete node types (as it's part of core package, whereas impls are part of mapper package)Factory method for constructing properly initializedJsonGeneratorto write content using specifiedDataOutput.createGenerator(File outputFile, JsonEncoding enc) Factory method for constructing properly initializedJsonGeneratorto write content to specifiedFile, using specified encoding.Factory method for constructing properly initializedJsonGeneratorto write content using specifiedOutputStream.createGenerator(OutputStream out, JsonEncoding enc) Factory method for constructing properly initializedJsonGeneratorto write content using specifiedOutputStreamand encoding.Factory method for constructing properly initializedJsonGeneratorto write content using specifiedWriter.Factory method for constructing properly initializedJsonParserto read content using non-blocking (asynchronous) mode.Note: return type is co-variant, as basic ObjectCodec abstraction cannot refer to concrete node types (as it's part of core package, whereas impls are part of mapper package)createParser(byte[] content) Factory method for constructing properly initializedJsonParserto read content from specified byte array.createParser(byte[] content, int offset, int len) Factory method for constructing properly initializedJsonParserto read content from specified byte array.createParser(char[] content) Factory method for constructing properly initializedJsonParserto read content from specified character array Parser is not managed (or "owned") by ObjectMapper: caller is responsible for properly closing it once content reading is complete.createParser(char[] content, int offset, int len) Factory method for constructing properly initializedJsonParserto read content from specified character array.createParser(DataInput content) Factory method for constructing properly initializedJsonParserto read content using specifiedDataInput.createParser(File src) Factory method for constructing properly initializedJsonParserto read content from specifiedFile.Factory method for constructing properly initializedJsonParserto read content using specifiedInputStream.Factory method for constructing properly initializedJsonParserto read content using specifiedReader.createParser(String content) Factory method for constructing properly initializedJsonParserto read content from specified String.createParser(URL src) Factory method for constructing properly initializedJsonParserto read content from specifiedFile.Method for disabling automatic inclusion of type information; if so, only explicitly annotated types (ones withJsonTypeInfo) will have additional embedded type information.disable(JsonGenerator.Feature... features) Method for disabling specifiedJsonGenerator.Features for parser instances this object mapper creates.disable(JsonParser.Feature... features) Method for disabling specifiedJsonParser.Features for parser instances this object mapper creates.disable(DeserializationFeature feature) Method for disabling specifiedDeserializationConfigfeatures.disable(DeserializationFeature first, DeserializationFeature... f) Method for disabling specifiedDeserializationConfigfeatures.disable(MapperFeature... f) Deprecated.Since 2.13 useJsonMapper.builder().disable(...)Method for disabling specifiedDeserializationConfigfeatures.disable(SerializationFeature first, SerializationFeature... f) Method for disabling specifiedDeserializationConfigfeatures.Deprecated.Since 2.10 usedeactivateDefaultTyping()insteadenable(JsonGenerator.Feature... features) Method for enabling specifiedJsonGenerator.Features for parser instances this object mapper creates.enable(JsonParser.Feature... features) Method for enabling specifiedJsonParser.Features for parser instances this object mapper creates.enable(DeserializationFeature feature) Method for enabling specifiedDeserializationConfigfeatures.enable(DeserializationFeature first, DeserializationFeature... f) Method for enabling specifiedDeserializationConfigfeatures.enable(MapperFeature... f) Deprecated.Since 2.13 useJsonMapper.builder().enable(...)Method for enabling specifiedDeserializationConfigfeature.enable(SerializationFeature first, SerializationFeature... f) Method for enabling specifiedDeserializationConfigfeatures.Deprecated.Since 2.10 useactivateDefaultTyping(PolymorphicTypeValidator)insteadDeprecated.Since 2.10 useactivateDefaultTyping(PolymorphicTypeValidator,DefaultTyping)insteadenableDefaultTyping(ObjectMapper.DefaultTyping applicability, JsonTypeInfo.As includeAs) Deprecated.Since 2.10 useactivateDefaultTyping(PolymorphicTypeValidator,DefaultTyping,JsonTypeInfo.As)insteadenableDefaultTypingAsProperty(ObjectMapper.DefaultTyping applicability, String propertyName) Deprecated.Since 2.10 useactivateDefaultTypingAsProperty(PolymorphicTypeValidator,DefaultTyping,String)insteadConvenience method that is functionally equivalent to:mapper.registerModules(mapper.findModules());Class<?> findMixInClassFor(Class<?> cls) Method for locating available methods, using JDKServiceLoaderfacility, along with module-provided SPI.findModules(ClassLoader classLoader) Method for locating available methods, using JDKServiceLoaderfacility, along with module-provided SPI.generateJsonSchema(Class<?> t) Deprecated.Since 2.6 use external JSON Schema generator (jackson-module-jsonSchema) (which under the hood callsacceptJsonFormatVisitor(JavaType, JsonFormatVisitorWrapper))Method that returns the shared defaultDeserializationConfigobject that defines configuration settings for deserialization.Method for getting currentDeserializationContext.Accessor for finding underlying data format factory (JsonFactory) codec will use for data binding.Method that can be used to get hold ofJsonNodeFactorythat this mapper will use when directly constructing rootJsonNodeinstances for Trees.Accessor for configuredPolymorphicTypeValidatorused for validating polymorphic subtypes used with explicit polymorphic types (annotation-based), but NOT one with "default typing" (seeactivateDefaultTyping(PolymorphicTypeValidator)for details).The set ofModuletypeIds that are registered in this ObjectMapper, if (and only if!)MapperFeature.IGNORE_DUPLICATE_MODULE_REGISTRATIONSis enabled AND module being added returns non-nullvalue for itsModule.getTypeId().Method that returns the shared defaultSerializationConfigobject that defines configuration settings for serialization.Method for getting currentSerializerFactory.Accessor for the "blueprint" (or, factory) instance, from which instances are created by callingDefaultSerializerProvider.createInstance(com.fasterxml.jackson.databind.SerializationConfig, com.fasterxml.jackson.databind.ser.SerializerFactory).Accessor for constructing and returning aSerializerProviderinstance that may be used for accessing serializers.Method for accessing subtype resolver in use.Accessor for getting currently configuredTypeFactoryinstance.Method for accessing currently configured visibility checker; object used for determining whether given property element (method, field, constructor) can be auto-detected or not.booleanConvenience method, equivalent to:booleanbooleanbooleanbooleanbooleanMethod for checking whether given deserialization-specific feature is enabled.booleanMethod for checking whether givenMapperFeatureis enabled.booleanMethod for checking whether given serialization-specific feature is enabled.intnullNode()reader()Factory method for constructingObjectReaderwith default settings.reader(Base64Variant defaultBase64) Factory method for constructingObjectReaderthat will use specified Base64 encoding variant for Base64-encoded binary data.reader(FormatSchema schema) Factory method for constructingObjectReaderthat will pass specific schema object toJsonParserused for reading content.reader(TypeReference<?> type) Deprecated.Since 2.5, usereaderFor(TypeReference)insteadreader(ContextAttributes attrs) Factory method for constructingObjectReaderthat will use specified default attributes.reader(DeserializationFeature feature) Factory method for constructingObjectReaderwith specified feature enabled (compared to settings that this mapper instance has).reader(DeserializationFeature first, DeserializationFeature... other) Factory method for constructingObjectReaderwith specified features enabled (compared to settings that this mapper instance has).reader(InjectableValues injectableValues) Factory method for constructingObjectReaderthat will use specified injectable values.Deprecated.Since 2.5, usereaderFor(JavaType)insteadreader(JsonNodeFactory nodeFactory) Factory method for constructingObjectReaderthat will use specifiedJsonNodeFactoryfor constructing JSON trees.Deprecated.Since 2.5, usereaderFor(Class)insteadreaderFor(TypeReference<?> typeRef) Factory method for constructingObjectReaderthat will read or update instances of specified typeFactory method for constructingObjectReaderthat will read or update instances of specified typeFactory method for constructingObjectReaderthat will read or update instances of specified typereaderForArrayOf(Class<?> type) Factory method for constructingObjectReaderthat will read values of a typeList<type>.readerForListOf(Class<?> type) Factory method for constructingObjectReaderthat will read or update instances of a typeList<type>.readerForMapOf(Class<?> type) Factory method for constructingObjectReaderthat will read or update instances of a typeMap<String, type>Functionally same as:readerForUpdating(Object valueToUpdate) Factory method for constructingObjectReaderthat will update given Object (usually Bean, but can be a Collection or Map as well, but NOT an array) with JSON data.readerWithView(Class<?> view) Factory method for constructingObjectReaderthat will deserialize objects using specified JSON View (filter).readTree(byte[] content) Same asreadTree(InputStream)except content read from passed-in byte array.readTree(byte[] content, int offset, int len) Same asreadTree(InputStream)except content read from passed-in byte array.<T extends TreeNode>
TMethod to deserialize JSON content as a treeJsonNode.Same asreadTree(InputStream)except content read from passed-inFile.readTree(InputStream in) Method to deserialize JSON content as tree expressed using set ofJsonNodeinstances.Same asreadTree(InputStream)except content accessed through passed-inReaderSame asreadTree(InputStream)except content read from passed-inStringSame asreadTree(InputStream)except content read from passed-inURL.<T> TreadValue(byte[] src, int offset, int len, TypeReference<T> valueTypeRef) <T> T<T> T<T> TreadValue(byte[] src, TypeReference<T> valueTypeRef) <T> T<T> Tfinal <T> TreadValue(JsonParser p, ResolvedType valueType) Method to deserialize JSON content into a Java type, reference to which is passed as argument.<T> TreadValue(JsonParser p, TypeReference<T> valueTypeRef) Method to deserialize JSON content into a Java type, reference to which is passed as argument.<T> TreadValue(JsonParser p, JavaType valueType) Type-safe overloaded method, basically alias forreadValue(JsonParser, Class).<T> TreadValue(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 (likeBoolean).<T> T<T> T<T> TreadValue(File src, TypeReference<T> valueTypeRef) Method to deserialize JSON content from given file into given Java type.<T> TMethod to deserialize JSON content from given file into given Java type.<T> TMethod to deserialize JSON content from given file into given Java type.<T> TreadValue(InputStream src, TypeReference<T> valueTypeRef) <T> TreadValue(InputStream src, JavaType valueType) <T> TreadValue(InputStream src, Class<T> valueType) <T> TreadValue(Reader src, TypeReference<T> valueTypeRef) <T> T<T> T<T> TreadValue(String content, TypeReference<T> valueTypeRef) Method to deserialize JSON content from given JSON content String.<T> TMethod to deserialize JSON content from given JSON content String.<T> TMethod to deserialize JSON content from given JSON content String.<T> TreadValue(URL src, TypeReference<T> valueTypeRef) Same asreadValue(java.net.URL, Class)except that target specified byTypeReference.<T> TSame asreadValue(java.net.URL, Class)except that target specified byJavaType.<T> TMethod to deserialize JSON content from given resource into given Java type.<T> MappingIterator<T> readValues(JsonParser p, ResolvedType valueType) Convenience method, equivalent in function to:<T> MappingIterator<T> readValues(JsonParser p, TypeReference<T> valueTypeRef) Method for reading sequence of Objects from parser stream.<T> MappingIterator<T> readValues(JsonParser p, JavaType valueType) Convenience method, equivalent in function to:<T> MappingIterator<T> readValues(JsonParser p, Class<T> valueType) Convenience method, equivalent in function to: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.registerModules(Module... modules) Convenience method for registering specified modules in order; functionally equivalent to:registerModules(Iterable<? extends Module> modules) Convenience method for registering specified modules in order; functionally equivalent to:voidregisterSubtypes(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).voidregisterSubtypes(Class<?>... classes) Method for registering specified class as a subtype, so that typename-based resolution can link supertypes to subtypes (as an alternative to using annotations).voidregisterSubtypes(Collection<Class<?>> subtypes) Method for setting custom accessor naming strategy to use.Method for settingAnnotationIntrospectorused by this mapper instance for both serialization and deserialization.setAnnotationIntrospectors(AnnotationIntrospector serializerAI, AnnotationIntrospector deserializerAI) Method for changingAnnotationIntrospectorinstances used by this mapper instance for serialization and deserialization, specifying them separately so that different introspection can be used for different aspectsMethod that will configure defaultBase64Variantthatbyte[]serializers and deserializers will use.setCacheProvider(CacheProvider cacheProvider) Method for specifyingCacheProviderinstance, to provide Cache instances to be used in components downstream.setConfig(DeserializationConfig config) Method that allows overriding of the underlyingDeserializationConfigobject.setConfig(SerializationConfig config) Method that allows overriding of the underlyingSerializationConfigobject, which contains serialization-specific configuration settings.Method for specifyingConstructorDetectorto use for determining some aspects of creator auto-detection (specifically auto-detection of constructor, and in particular behavior with single-argument constructors).setDateFormat(DateFormat dateFormat) Method for configuring the defaultDateFormatto use when serializing time values as Strings, and deserializing from JSON Strings.NOTE: preferred way to set the defaults is to useBuilderstyle construction, seeJsonMapper.builder()(andMapperBuilder.defaultAttributes(com.fasterxml.jackson.databind.cfg.ContextAttributes)).Method for setting default Setter configuration, regarding things like merging, null-handling; used for properties for which there are no per-type or per-property overrides (via annotations or config overrides).Method for specifyingPrettyPrinterto use when "default pretty-printing" is enabled (by enablingSerializationFeature.INDENT_OUTPUT)Short-cut for:Method for setting default POJO property inclusion strategy for serialization, applied for all properties for which there are no per-type or per-property overrides (via annotations or config overrides).Method for setting default Setter configuration, regarding things like merging, null-handling; used for properties for which there are no per-type or per-property overrides (via annotations or config overrides).setDefaultTyping(TypeResolverBuilder<?> typer) Method for enabling automatic inclusion of type information ("Default Typing"), using specified handler object for determining which types this affects, as well as details of how information is embedded.Method for setting auto-detection visibility definition defaults, which are in effect unless overridden by annotations (likeJsonAutoDetect) or per-type visibility overrides.setFilterProvider(FilterProvider filterProvider) Method for configuring this mapper to use specifiedFilterProviderfor mapping Filter Ids to actual filter instances.voidsetFilters(FilterProvider filterProvider) Deprecated.Since 2.6, usesetFilterProvider(com.fasterxml.jackson.databind.ser.FilterProvider)instead (allows chaining)Method for configuringHandlerInstantiatorto use for creating instances of handlers (such as serializers, deserializers, type and type id resolvers), given a class.setInjectableValues(InjectableValues injectableValues) Method for configuringInjectableValueswhich used to find values to inject.Method for overriding default locale to use for formatting.voidsetMixInAnnotations(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<?>>).Method that can be called to specify given resolver for locating mix-in classes to use, overriding directly added mappings.Method to use for defining mix-in annotations to use for augmenting annotations that processable (serializable / deserializable) classes have.Method for specifyingJsonNodeFactoryto use for constructing root level tree nodes (via methodcreateObjectNode()Method for specifyingPolymorphicTypeValidatorto use for validating polymorphic subtypes used with explicit polymorphic types (annotation-based), but NOT one with "default typing" (seeactivateDefaultTyping(PolymorphicTypeValidator)for details).Deprecated.Method for setting custom property naming strategy to use.Convenience method, equivalent to calling:Method for setting specificSerializerFactoryto use for constructing (bean) serializers.Method for setting "blueprint"SerializerProviderinstance to use as the base for actual provider instances to use for handling caching ofJsonSerializerinstances.Method for setting custom subtype resolver to use.setTimeZone(TimeZone tz) Method for overriding default TimeZone to use for formatting.Method that can be used to overrideTypeFactoryinstance used by this mapper.setVisibility(PropertyAccessor forMethod, JsonAutoDetect.Visibility visibility) Convenience method that allows changing configuration for underlyingVisibilityCheckers, to change details of what kinds of properties are auto-detected.setVisibility(VisibilityChecker<?> vc) Method for setting currently configured defaultVisibilityChecker, object used for determining whether given property element (method, field, constructor) can be auto-detected or not.voidDeprecated.Since 2.6 usesetVisibility(VisibilityChecker)instead.Method that can be used to get hold ofJsonFactorythat this mapper uses if it needs to constructJsonParsers and/orJsonGenerators.Method for constructing aJsonParserout of JSON tree representation.<T> TtreeToValue(TreeNode n, TypeReference<T> toValueTypeRef) Same astreeToValue(TreeNode, JavaType)but target type specified using fully resolvedTypeReference.<T> TtreeToValue(TreeNode n, JavaType valueType) Same astreeToValue(TreeNode, Class)but target type specified using fully resolvedJavaType.<T> TtreeToValue(TreeNode n, Class<T> valueType) Convenience conversion method that will bind data given JSON tree contains into specific value (usually bean) type.<T> TupdateValue(T valueToUpdate, Object overrides) Convenience method similar toconvertValue(Object, JavaType)but one in which<T extends JsonNode>
TvalueToTree(Object fromValue) Method that is reverse oftreeToValue(com.fasterxml.jackson.core.TreeNode, java.lang.Class<T>): it will convert given Java value (usually bean) into its equivalent Tree modeJsonNoderepresentation.version()Method that will return version information stored in and read from jar that contains this class.writer()Convenience method for constructingObjectWriterwith default settings.writer(Base64Variant defaultBase64) Factory method for constructingObjectWriterthat will use specified Base64 encoding variant for Base64-encoded binary data.writer(FormatSchema schema) Factory method for constructingObjectWriterthat will pass specific schema object toJsonGeneratorused for writing content.writer(CharacterEscapes escapes) Factory method for constructingObjectReaderthat will use specified character escaping details for output.writer(PrettyPrinter pp) Factory method for constructingObjectWriterthat will serialize objects using specified pretty printer for indentation (or if null, no pretty printer)writer(ContextAttributes attrs) Factory method for constructingObjectWriterthat will use specified default attributes.writer(FilterProvider filterProvider) Factory method for constructingObjectWriterthat will serialize objects using specified filter provider.writer(SerializationFeature feature) Factory method for constructingObjectWriterwith specified feature enabled (compared to settings that this mapper instance has).writer(SerializationFeature first, SerializationFeature... other) Factory method for constructingObjectWriterwith specified features enabled (compared to settings that this mapper instance has).writer(DateFormat df) Factory method for constructingObjectWriterthat will serialize objects using specifiedDateFormat; or, if null passed, using timestamp (64-bit number.writerFor(TypeReference<?> rootType) Factory method for constructingObjectWriterthat will serialize objects using specified root type, instead of actual runtime type of value.Factory method for constructingObjectWriterthat will serialize objects using specified root type, instead of actual runtime type of value.Factory method for constructingObjectWriterthat will serialize objects using specified root type, instead of actual runtime type of value.Factory method for constructingObjectWriterthat will serialize objects using the default pretty printer for indentationwriterWithType(TypeReference<?> rootType) Deprecated.Since 2.5, usewriterFor(TypeReference)insteadwriterWithType(JavaType rootType) Deprecated.Since 2.5, usewriterFor(JavaType)insteadwriterWithType(Class<?> rootType) Deprecated.Since 2.5, usewriterFor(Class)insteadwriterWithView(Class<?> serializationView) Factory method for constructingObjectWriterthat will serialize objects using specified JSON View (filter).voidwriteTree(JsonGenerator g, TreeNode rootNode) Method for serializing JSON content from given Tree instance, using specified generator.voidwriteTree(JsonGenerator g, JsonNode rootNode) Method to serialize given JSON Tree, using generator provided.voidwriteValue(JsonGenerator g, Object value) Method that can be used to serialize any Java value as JSON output, using providedJsonGenerator.voidwriteValue(DataOutput out, Object value) voidwriteValue(File resultFile, Object value) Method that can be used to serialize any Java value as JSON output, written to File provided.voidwriteValue(OutputStream out, Object value) Method that can be used to serialize any Java value as JSON output, using output stream provided (using encodingJsonEncoding.UTF8).voidwriteValue(Writer w, Object value) Method that can be used to serialize any Java value as JSON output, using Writer provided.byte[]writeValueAsBytes(Object value) Method that can be used to serialize any Java value as a byte array.writeValueAsString(Object value) Method that can be used to serialize any Java value as a String.Methods inherited from class com.fasterxml.jackson.core.ObjectCodec
getJsonFactory
-
Constructor Details
-
ObjectMapper
public ObjectMapper()Default constructor, which will construct the defaultJsonFactoryas necessary, useSerializerProvideras itsSerializerProvider, andBeanSerializerFactoryas itsSerializerFactory. This means that it can serialize all standard JDK types, as well as regular Java Beans (based on method names and Jackson-specific annotations), but does not support JAXB annotations. -
ObjectMapper
Constructs instance that uses specifiedJsonFactoryfor constructing necessaryJsonParsers and/orJsonGenerators. -
ObjectMapper
Constructs instance that uses specifiedJsonFactoryfor constructing necessaryJsonParsers and/orJsonGenerators, and uses given providers for accessing serializers and deserializers.- Parameters:
jf- JsonFactory to use: if null, a newMappingJsonFactorywill be constructedsp- SerializerProvider to use: if null, aSerializerProviderwill be constructeddc- Blueprint deserialization context instance to use for creating actual context objects; if null, will construct standardDeserializationContext
-
-
Method Details
-
copy
Method for creating a newObjectMapperinstance that has same initial configuration as this instance. Note that this also requires making a copy of the underlyingJsonFactoryinstance.Method is typically used when multiple, differently configured mappers are needed. Although configuration is shared, cached serializers and deserializers are NOT shared, which means that the new instance may be re-configured before use; meaning that it behaves the same way as if an instance was constructed from scratch.
- Since:
- 2.1
-
copyWith
Method for creating a newObjectMapper. Differs from a regular copy, as aJsonFactoryto be used can be passed as an argument, which will be used to create the copy rather than the one present on the object to be copied.- Parameters:
factory- JsonFactory to be used.- Returns:
- ObjectMapper
- Since:
- 2.14
-
version
Method that will return version information stored in and read from jar that contains this class.- Specified by:
versionin interfaceVersioned- Specified by:
versionin classObjectCodec- Returns:
- Version of the component
-
registerModule
Method for registering a module that can extend functionality provided by this mapper; for example, by adding providers for custom serializers and deserializers.- Parameters:
module- Module to register
-
registerModules
Convenience method for registering specified modules in order; functionally equivalent to:for (Module module : modules) { registerModule(module); }- Since:
- 2.2
-
registerModules
Convenience method for registering specified modules in order; functionally equivalent to:for (Module module : modules) { registerModule(module); }- Since:
- 2.2
-
getRegisteredModuleIds
The set ofModuletypeIds that are registered in this ObjectMapper, if (and only if!)MapperFeature.IGNORE_DUPLICATE_MODULE_REGISTRATIONSis enabled AND module being added returns non-nullvalue for itsModule.getTypeId().NOTE: when using the default
SimpleModuleconstructor, its id is specified asnulland as a consequence such module is NOT included in returned set.- Since:
- 2.9.6
-
findModules
Method for locating available methods, using JDKServiceLoaderfacility, along with module-provided SPI.Note that method does not do any caching, so calls should be considered potentially expensive.
- Since:
- 2.2
-
findModules
Method for locating available methods, using JDKServiceLoaderfacility, along with module-provided SPI.Note that method does not do any caching, so calls should be considered potentially expensive.
- Since:
- 2.2
-
findAndRegisterModules
Convenience method that is functionally equivalent to:mapper.registerModules(mapper.findModules());As with
findModules(), no caching is done for modules, so care needs to be taken to either create and share a single mapper instance; or to cache introspected set of modules.- Since:
- 2.2
-
createGenerator
Factory method for constructing properly initializedJsonGeneratorto write content using specifiedOutputStream. Generator is not managed (or "owned") by mapper: caller is responsible for properly closing it once content generation is complete.- Throws:
IOException- Since:
- 2.11
-
createGenerator
Factory method for constructing properly initializedJsonGeneratorto write content using specifiedOutputStreamand encoding. Generator is not managed (or "owned") by mapper: caller is responsible for properly closing it once content generation is complete.- Throws:
IOException- Since:
- 2.11
-
createGenerator
Factory method for constructing properly initializedJsonGeneratorto write content using specifiedWriter. Generator is not managed (or "owned") by mapper: caller is responsible for properly closing it once content generation is complete.- Throws:
IOException- Since:
- 2.11
-
createGenerator
Factory method for constructing properly initializedJsonGeneratorto write content to specifiedFile, using specified encoding. Generator is not managed (or "owned") by mapper: caller is responsible for properly closing it once content generation is complete.- Throws:
IOException- Since:
- 2.11
-
createGenerator
Factory method for constructing properly initializedJsonGeneratorto write content using specifiedDataOutput. Generator is not managed (or "owned") by mapper: caller is responsible for properly closing it once content generation is complete.- Throws:
IOException- Since:
- 2.11
-
createParser
Factory method for constructing properly initializedJsonParserto read content from specifiedFile. Parser is not managed (or "owned") by ObjectMapper: caller is responsible for properly closing it once content reading is complete.- Throws:
IOException- Since:
- 2.11
-
createParser
Factory method for constructing properly initializedJsonParserto read content from specifiedFile. Parser is not managed (or "owned") by ObjectMapper: caller is responsible for properly closing it once content reading is complete.- Throws:
IOException- Since:
- 2.11
-
createParser
Factory method for constructing properly initializedJsonParserto read content using specifiedInputStream. Parser is not managed (or "owned") by ObjectMapper: caller is responsible for properly closing it once content reading is complete.- Throws:
IOException- Since:
- 2.11
-
createParser
Factory method for constructing properly initializedJsonParserto read content using specifiedReader. Parser is not managed (or "owned") by ObjectMapper: caller is responsible for properly closing it once content reading is complete.- Throws:
IOException- Since:
- 2.11
-
createParser
Factory method for constructing properly initializedJsonParserto read content from specified byte array. Parser is not managed (or "owned") by ObjectMapper: caller is responsible for properly closing it once content reading is complete.- Throws:
IOException- Since:
- 2.11
-
createParser
Factory method for constructing properly initializedJsonParserto read content from specified byte array. Parser is not managed (or "owned") by ObjectMapper: caller is responsible for properly closing it once content reading is complete.- Throws:
IOException- Since:
- 2.11
-
createParser
Factory method for constructing properly initializedJsonParserto read content from specified String. Parser is not managed (or "owned") by ObjectMapper: caller is responsible for properly closing it once content reading is complete.- Throws:
IOException- Since:
- 2.11
-
createParser
Factory method for constructing properly initializedJsonParserto read content from specified character array Parser is not managed (or "owned") by ObjectMapper: caller is responsible for properly closing it once content reading is complete.- Throws:
IOException- Since:
- 2.11
-
createParser
Factory method for constructing properly initializedJsonParserto read content from specified character array. Parser is not managed (or "owned") by ObjectMapper: caller is responsible for properly closing it once content reading is complete.- Throws:
IOException- Since:
- 2.11
-
createParser
Factory method for constructing properly initializedJsonParserto read content using specifiedDataInput. Parser is not managed (or "owned") by ObjectMapper: caller is responsible for properly closing it once content reading is complete.- Throws:
IOException- Since:
- 2.11
-
createNonBlockingByteArrayParser
Factory method for constructing properly initializedJsonParserto read content using non-blocking (asynchronous) mode. Parser is not managed (or "owned") by ObjectMapper: caller is responsible for properly closing it once content reading is complete.- Throws:
IOException- Since:
- 2.11
-
getSerializationConfig
Method that returns the shared defaultSerializationConfigobject that defines configuration settings for serialization.Note that since instances are immutable, you can NOT change settings by accessing an instance and calling methods: this will simply create new instance of config object.
-
getDeserializationConfig
Method that returns the shared defaultDeserializationConfigobject that defines configuration settings for deserialization.Note that since instances are immutable, you can NOT change settings by accessing an instance and calling methods: this will simply create new instance of config object.
-
getDeserializationContext
Method for getting currentDeserializationContext.Note that since instances are immutable, you can NOT change settings by accessing an instance and calling methods: this will simply create new instance of context object.
-
setSerializerFactory
Method for setting specificSerializerFactoryto use for constructing (bean) serializers. -
getSerializerFactory
Method for getting currentSerializerFactory.Note that since instances are immutable, you can NOT change settings by accessing an instance and calling methods: this will simply create new instance of factory object.
-
setSerializerProvider
Method for setting "blueprint"SerializerProviderinstance to use as the base for actual provider instances to use for handling caching ofJsonSerializerinstances. -
getSerializerProvider
Accessor for the "blueprint" (or, factory) instance, from which instances are created by callingDefaultSerializerProvider.createInstance(com.fasterxml.jackson.databind.SerializationConfig, com.fasterxml.jackson.databind.ser.SerializerFactory). Note that returned instance cannot be directly used as it is not properly configured: to get a properly configured instance to call, usegetSerializerProviderInstance()instead. -
getSerializerProviderInstance
Accessor for constructing and returning aSerializerProviderinstance that may be used for accessing serializers. This is same as callinggetSerializerProvider(), and callingcreateInstance()on it.- Since:
- 2.7
-
setMixIns
Method to use for defining mix-in annotations to use for augmenting annotations that processable (serializable / deserializable) classes have. Mixing in is done when introspecting class annotations and properties. Map passed contains keys that are target classes (ones to augment with new annotation overrides), and values that are source classes (have annotations to use for augmentation). Annotations from source classes (and their supertypes) will override annotations that target classes (and their super-types) have.Note that this method will CLEAR any previously defined mix-ins for this mapper.
- Since:
- 2.5
-
addMixIn
Method to use for adding mix-in annotations to use for augmenting specified class or interface. All annotations frommixinSourceare taken to override annotations thattarget(or its supertypes) has.- Parameters:
target- Class (or interface) whose annotations to effectively overridemixinSource- Class (or interface) whose annotations are to be "added" to target's annotations, overriding as necessary- Since:
- 2.5
-
setMixInResolver
Method that can be called to specify given resolver for locating mix-in classes to use, overriding directly added mappings. Note that direct mappings are not cleared, but they are only applied if resolver does not provide mix-in matches.- Since:
- 2.6
-
findMixInClassFor
-
mixInCount
public int mixInCount() -
setMixInAnnotations
Deprecated.Since 2.5: replaced by a fluent form of the method;setMixIns(java.util.Map<java.lang.Class<?>, java.lang.Class<?>>). -
addMixInAnnotations
Deprecated.Since 2.5: replaced by a fluent form of the method;addMixIn(Class, Class). -
getVisibilityChecker
Method for accessing currently configured visibility checker; object used for determining whether given property element (method, field, constructor) can be auto-detected or not. -
setVisibility
Method for setting currently configured defaultVisibilityChecker, object used for determining whether given property element (method, field, constructor) can be auto-detected or not. This default checker is used as the base visibility: per-class overrides (both via annotations and per-type config overrides) can further change these settings.- Since:
- 2.6
-
setVisibility
Convenience method that allows changing configuration for underlyingVisibilityCheckers, to change details of what kinds of properties are auto-detected. Basically short cut for doing:mapper.setVisibilityChecker( mapper.getVisibilityChecker().withVisibility(forMethod, visibility) );one common use case would be to do:mapper.setVisibility(JsonMethod.FIELD, Visibility.ANY);
which would make all member fields serializable without further annotations, instead of just public fields (default setting).- Parameters:
forMethod- Type of property descriptor affected (field, getter/isGetter, setter, creator)visibility- Minimum visibility to require for the property descriptors of type- Returns:
- Modified mapper instance (that is, "this"), to allow chaining of configuration calls
-
getSubtypeResolver
Method for accessing subtype resolver in use. -
setSubtypeResolver
Method for setting custom subtype resolver to use. -
setAnnotationIntrospector
Method for settingAnnotationIntrospectorused by this mapper instance for both serialization and deserialization. Note that doing this will replace the current introspector, which may lead to unavailability of core Jackson annotations. If you want to combine handling of multiple introspectors, have a look atAnnotationIntrospectorPair.- See Also:
-
setAnnotationIntrospectors
public ObjectMapper setAnnotationIntrospectors(AnnotationIntrospector serializerAI, AnnotationIntrospector deserializerAI) Method for changingAnnotationIntrospectorinstances used by this mapper instance for serialization and deserialization, specifying them separately so that different introspection can be used for different aspects- Parameters:
serializerAI-AnnotationIntrospectorto use for configuring serializationdeserializerAI-AnnotationIntrospectorto use for configuring deserialization- Since:
- 2.1
- See Also:
-
setPropertyNamingStrategy
Method for setting custom property naming strategy to use. -
getPropertyNamingStrategy
- Since:
- 2.5
-
setAccessorNaming
Method for setting custom accessor naming strategy to use.- Since:
- 2.12
-
setDefaultPrettyPrinter
Method for specifyingPrettyPrinterto use when "default pretty-printing" is enabled (by enablingSerializationFeature.INDENT_OUTPUT)- Parameters:
pp- Pretty printer to use by default.- Returns:
- This mapper, useful for call-chaining
- Since:
- 2.6
-
setVisibilityChecker
Deprecated.Since 2.6 usesetVisibility(VisibilityChecker)instead. -
setPolymorphicTypeValidator
Method for specifyingPolymorphicTypeValidatorto use for validating polymorphic subtypes used with explicit polymorphic types (annotation-based), but NOT one with "default typing" (seeactivateDefaultTyping(PolymorphicTypeValidator)for details).- Since:
- 2.10
-
getPolymorphicTypeValidator
Accessor for configuredPolymorphicTypeValidatorused for validating polymorphic subtypes used with explicit polymorphic types (annotation-based), but NOT one with "default typing" (seeactivateDefaultTyping(PolymorphicTypeValidator)for details).- Since:
- 2.10
-
setSerializationInclusion
Convenience method, equivalent to calling:setPropertyInclusion(JsonInclude.Value.construct(incl, incl));
NOTE: behavior differs slightly from 2.8, where second argument was implied to be
JsonInclude.Include.ALWAYS. -
setPropertyInclusion
Deprecated.- Since:
- 2.7
-
setDefaultPropertyInclusion
Method for setting default POJO property inclusion strategy for serialization, applied for all properties for which there are no per-type or per-property overrides (via annotations or config overrides).- Since:
- 2.9 (basically rename of
setPropertyInclusion)
-
setDefaultPropertyInclusion
Short-cut for:setDefaultPropertyInclusion(JsonInclude.Value.construct(incl, incl));
- Since:
- 2.9 (basically rename of
setPropertyInclusion)
-
setDefaultSetterInfo
Method for setting default Setter configuration, regarding things like merging, null-handling; used for properties for which there are no per-type or per-property overrides (via annotations or config overrides).- Since:
- 2.9
-
setDefaultVisibility
Method for setting auto-detection visibility definition defaults, which are in effect unless overridden by annotations (likeJsonAutoDetect) or per-type visibility overrides.- Since:
- 2.9
-
setDefaultMergeable
Method for setting default Setter configuration, regarding things like merging, null-handling; used for properties for which there are no per-type or per-property overrides (via annotations or config overrides).- Since:
- 2.9
-
setDefaultLeniency
- Since:
- 2.10
-
registerSubtypes
Method for registering specified class as a subtype, so that typename-based resolution can link supertypes to subtypes (as an alternative to using annotations). Type for given class is determined from appropriate annotation; or if missing, default name (unqualified class name) -
registerSubtypes
Method for registering specified class as a subtype, so that typename-based resolution can link supertypes to subtypes (as an alternative to using annotations). Name may be provided as part of argument, but if not will be based on annotations or use default name (unqualified class name). -
registerSubtypes
- Since:
- 2.9
-
activateDefaultTyping
Convenience method that is equivalent to callingactivateDefaultTyping(ptv, DefaultTyping.OBJECT_AND_NON_CONCRETE);
NOTE: choice of
PolymorphicTypeValidatorto pass is critical for security as allowing all subtypes can be risky for untrusted content.- Parameters:
ptv- Validator used to verify that actual subtypes to deserialize are valid against whatever criteria validator uses: important in case where untrusted content is deserialized.- Since:
- 2.10
-
activateDefaultTyping
public ObjectMapper activateDefaultTyping(PolymorphicTypeValidator ptv, ObjectMapper.DefaultTyping applicability) Convenience method that is equivalent to callingactivateDefaultTyping(ptv, dti, JsonTypeInfo.As.WRAPPER_ARRAY);
NOTE: choice of
PolymorphicTypeValidatorto pass is critical for security as allowing all subtypes can be risky for untrusted content.- Parameters:
ptv- Validator used to verify that actual subtypes to deserialize are valid against whatever criteria validator uses: important in case where untrusted content is deserialized.applicability- Defines kinds of types for which additional type information is added; seeObjectMapper.DefaultTypingfor more information.- Since:
- 2.10
-
activateDefaultTyping
public ObjectMapper activateDefaultTyping(PolymorphicTypeValidator ptv, ObjectMapper.DefaultTyping applicability, JsonTypeInfo.As includeAs) Method for enabling automatic inclusion of type information ("Default Typing"), needed for proper deserialization of polymorphic types (unless types have been annotated withJsonTypeInfo).NOTE: use of
JsonTypeInfo.As#EXTERNAL_PROPERTYNOT SUPPORTED; and attempts of do so will throw anIllegalArgumentExceptionto make this limitation explicit.NOTE: choice of
PolymorphicTypeValidatorto pass is critical for security as allowing all subtypes can be risky for untrusted content.- Parameters:
ptv- Validator used to verify that actual subtypes to deserialize are valid against whatever criteria validator uses: important in case where untrusted content is deserialized.applicability- Defines kinds of types for which additional type information is added; seeObjectMapper.DefaultTypingfor more information.includeAs-- Since:
- 2.10
-
activateDefaultTypingAsProperty
public ObjectMapper activateDefaultTypingAsProperty(PolymorphicTypeValidator ptv, ObjectMapper.DefaultTyping applicability, String propertyName) Method for enabling automatic inclusion of type information ("Default Typing") -- needed for proper deserialization of polymorphic types (unless types have been annotated withJsonTypeInfo) -- using "As.PROPERTY" inclusion mechanism and specified property name to use for inclusion (default being "@class" since default type information always uses class name as type identifier)NOTE: choice of
PolymorphicTypeValidatorto pass is critical for security as allowing all subtypes can be risky for untrusted content.- Parameters:
ptv- Validator used to verify that actual subtypes to deserialize are valid against whatever criteria validator uses: important in case where untrusted content is deserialized.applicability- Defines kinds of types for which additional type information is added; seeObjectMapper.DefaultTypingfor more information.propertyName- Name of property used for including type id for polymorphic values.- Since:
- 2.10
-
deactivateDefaultTyping
Method for disabling automatic inclusion of type information; if so, only explicitly annotated types (ones withJsonTypeInfo) will have additional embedded type information.- Since:
- 2.10
-
setDefaultTyping
Method for enabling automatic inclusion of type information ("Default Typing"), using specified handler object for determining which types this affects, as well as details of how information is embedded.NOTE: use of Default Typing can be a potential security risk if incoming content comes from untrusted sources, so care should be taken to use a
TypeResolverBuilderthat can limit allowed classes to deserialize. Note in particular thatStdTypeResolverBuilderDOES NOT limit applicability but creates type (de)serializers for all types.- Parameters:
typer- Type information inclusion handler
-
enableDefaultTyping
Deprecated.Since 2.10 useactivateDefaultTyping(PolymorphicTypeValidator)instead -
enableDefaultTyping
Deprecated.Since 2.10 useactivateDefaultTyping(PolymorphicTypeValidator,DefaultTyping)instead -
enableDefaultTyping
@Deprecated public ObjectMapper enableDefaultTyping(ObjectMapper.DefaultTyping applicability, JsonTypeInfo.As includeAs) Deprecated.Since 2.10 useactivateDefaultTyping(PolymorphicTypeValidator,DefaultTyping,JsonTypeInfo.As)instead -
enableDefaultTypingAsProperty
@Deprecated public ObjectMapper enableDefaultTypingAsProperty(ObjectMapper.DefaultTyping applicability, String propertyName) Deprecated.Since 2.10 useactivateDefaultTypingAsProperty(PolymorphicTypeValidator,DefaultTyping,String)instead -
disableDefaultTyping
Deprecated.Since 2.10 usedeactivateDefaultTyping()instead -
configOverride
Accessor for getting a mutable configuration override object for given type, needed to add or change per-type overrides applied to properties of given type. Usage is through returned object by calling "setter" methods, which directly modify override object and take effect directly. For example you can domapper.configOverride(java.util.Date.class) .setFormat(JsonFormat.Value.forPattern("yyyy-MM-dd"));to change the default format to use for properties of typeDate(possibly further overridden by per-property annotations)- Since:
- 2.8
-
coercionConfigDefaults
Accessor forMutableCoercionConfigthrough which default (fallback) coercion configurations can be changed. Note that such settings are only applied if more specific (by logical and physical type) configuration have not been defined.NOTE: Preferred access method and point is through
Builderstyle construction, seeJsonMapper.BuilderandMapperBuilder.withCoercionConfigDefaults(Consumer).- Since:
- 2.12
-
coercionConfigFor
Accessor forMutableCoercionConfigthrough which coercion configuration for specified logical target type can be set.NOTE: Preferred access method and point is through
Builderstyle construction, seeJsonMapper.BuilderandMapperBuilder.withCoercionConfig(LogicalType, Consumer).- Since:
- 2.12
-
coercionConfigFor
Accessor forMutableCoercionConfigthrough which coercion configuration for specified physical target type can be set.NOTE: Preferred access method and point is through
Builderstyle construction, seeJsonMapper.BuilderandMapperBuilder.withCoercionConfig(Class, Consumer)(Consumer)}.- Since:
- 2.12
-
getTypeFactory
Accessor for getting currently configuredTypeFactoryinstance. -
setTypeFactory
Method that can be used to overrideTypeFactoryinstance used by this mapper.Note: will also set
TypeFactorythat deserialization and serialization config objects use. -
constructType
Convenience method for constructingJavaTypeout of given type (typicallyjava.lang.Class), but without explicit context. -
constructType
Convenience method for constructingJavaTypeout of given type reference.- Since:
- 2.12
-
getNodeFactory
Method that can be used to get hold ofJsonNodeFactorythat this mapper will use when directly constructing rootJsonNodeinstances for Trees.Note: this is just a shortcut for calling
getDeserializationConfig().getNodeFactory()
-
setNodeFactory
Method for specifyingJsonNodeFactoryto use for constructing root level tree nodes (via methodcreateObjectNode() -
setConstructorDetector
Method for specifyingConstructorDetectorto use for determining some aspects of creator auto-detection (specifically auto-detection of constructor, and in particular behavior with single-argument constructors).- Since:
- 2.12
-
setCacheProvider
Method for specifyingCacheProviderinstance, to provide Cache instances to be used in components downstream.- Throws:
IllegalArgumentException- if given provider is null- Since:
- 2.16
-
addHandler
Method for adding specifiedDeserializationProblemHandlerto be used for handling specific problems during deserialization. -
clearProblemHandlers
Method for removing all registeredDeserializationProblemHandlers instances from this mapper. -
setConfig
Method that allows overriding of the underlyingDeserializationConfigobject. It is added as a fallback method that may be used if no other configuration modifier method works: it should not be used if there are alternatives, and its use is generally discouraged.NOTE: only use this method if you know what you are doing -- it allows by-passing some of checks applied to other configuration methods. Also keep in mind that as with all configuration of
ObjectMapper, this is only thread-safe if done before calling any deserialization methods.- Since:
- 2.4
-
setFilters
Deprecated.Since 2.6, usesetFilterProvider(com.fasterxml.jackson.databind.ser.FilterProvider)instead (allows chaining) -
setFilterProvider
Method for configuring this mapper to use specifiedFilterProviderfor mapping Filter Ids to actual filter instances.Note that usually it is better to use method
writer(FilterProvider); however, sometimes this method is more convenient. For example, some frameworks only allow configuring of ObjectMapper instances and notObjectWriters.- Since:
- 2.6
-
setBase64Variant
Method that will configure defaultBase64Variantthatbyte[]serializers and deserializers will use.- Parameters:
v- Base64 variant to use- Returns:
- This mapper, for convenience to allow chaining
- Since:
- 2.1
-
setConfig
Method that allows overriding of the underlyingSerializationConfigobject, which contains serialization-specific configuration settings. It is added as a fallback method that may be used if no other configuration modifier method works: it should not be used if there are alternatives, and its use is generally discouraged.NOTE: only use this method if you know what you are doing -- it allows by-passing some of checks applied to other configuration methods. Also keep in mind that as with all configuration of
ObjectMapper, this is only thread-safe if done before calling any serialization methods.- Since:
- 2.4
-
tokenStreamFactory
Method that can be used to get hold ofJsonFactorythat this mapper uses if it needs to constructJsonParsers and/orJsonGenerators.WARNING: note that all
ObjectReaderandObjectWriterinstances created by this mapper usually share the same configuredJsonFactory, so changes to its configuration will "leak". To avoid such observed changes you should always use "with()" and "without()" method ofObjectReaderandObjectWriterfor changingJsonParser.FeatureandJsonGenerator.Featuresettings to use on per-call basis.- Returns:
JsonFactorythat this mapper uses when it needs to construct Json parser and generators- Since:
- 2.10
-
getFactory
Description copied from class:ObjectCodecAccessor for finding underlying data format factory (JsonFactory) codec will use for data binding.- Overrides:
getFactoryin classObjectCodec- Returns:
- Underlying
JsonFactoryinstance
-
setDateFormat
Method for configuring the defaultDateFormatto use when serializing time values as Strings, and deserializing from JSON Strings. This is preferably to directly modifyingSerializationConfigandDeserializationConfiginstances. If you need per-request configuration, usewriter(DateFormat)to create properly configuredObjectWriterand use that; this becauseObjectWriters are thread-safe whereas ObjectMapper itself is only thread-safe when configuring methods (such as this one) are NOT called. -
getDateFormat
- Since:
- 2.5
-
setHandlerInstantiator
Method for configuringHandlerInstantiatorto use for creating instances of handlers (such as serializers, deserializers, type and type id resolvers), given a class.- Parameters:
hi- Instantiator to use; if null, use the default implementation
-
setInjectableValues
Method for configuringInjectableValueswhich used to find values to inject. -
getInjectableValues
- Since:
- 2.6
-
setLocale
Method for overriding default locale to use for formatting. Default value used isLocale.getDefault(). -
setTimeZone
Method for overriding default TimeZone to use for formatting. Default value used is UTC (NOT default TimeZone of JVM). -
setDefaultAttributes
NOTE: preferred way to set the defaults is to use
Builderstyle construction, seeJsonMapper.builder()(andMapperBuilder.defaultAttributes(com.fasterxml.jackson.databind.cfg.ContextAttributes)).- Since:
- 2.13
-
isEnabled
Method for checking whether givenMapperFeatureis enabled. -
configure
Deprecated.Since 2.13 useJsonMapper.builder().configure(...) -
enable
Deprecated.Since 2.13 useJsonMapper.builder().enable(...) -
disable
Deprecated.Since 2.13 useJsonMapper.builder().disable(...) -
isEnabled
Method for checking whether given serialization-specific feature is enabled. -
configure
Method for changing state of an on/off serialization feature for this object mapper.Note: Changing the configuration of this
ObjectMapperinstance after its first use (read & write) is not safe and should not be attempted. Instead, usewith()andwithout()methods ofObjectReader/ObjectWriterwhich fully support reconfiguration as new instances are constructed.This method will be removed in Jackson 3.0 due to unsafe usage. Configure using
MapperBuilder.configure(SerializationFeature, boolean). -
enable
Method for enabling specifiedDeserializationConfigfeature. Modifies and returns this instance; no new object is created.Note: Changing the configuration of this
ObjectMapperinstance after its first use (read & write) is not safe and should not be attempted. Instead, usewith()andwithout()methods ofObjectReader/ObjectWriterwhich fully support reconfiguration as new instances are constructed.This method will be removed in Jackson 3.0 due to unsafe usage. Configure using
MapperBuilder.enable(SerializationFeature...). -
enable
Method for enabling specifiedDeserializationConfigfeatures. Modifies and returns this instance; no new object is created.Note: Changing the configuration of this
ObjectMapperinstance after its first use (read & write) is not safe and should not be attempted. Instead, usewith()andwithout()methods ofObjectReader/ObjectWriterwhich fully support reconfiguration as new instances are constructed.This method will be removed in Jackson 3.0 due to unsafe usage. Configure using
MapperBuilder.isEnabled(SerializationFeature). -
disable
Method for disabling specifiedDeserializationConfigfeatures. Modifies and returns this instance; no new object is created.Note: Changing the configuration of this
ObjectMapperinstance after its first use (read & write) is not safe and should not be attempted. Instead, usewith()andwithout()methods ofObjectReader/ObjectWriterwhich fully support reconfiguration as new instances are constructed.This method will be removed in Jackson 3.0 due to unsafe usage. Configure using
MapperBuilder.disable(SerializationFeature...). -
disable
Method for disabling specifiedDeserializationConfigfeatures. Modifies and returns this instance; no new object is created.Note: Changing the configuration of this
ObjectMapperinstance after its first use (read & write) is not safe and should not be attempted. Instead, usewith()andwithout()methods ofObjectReader/ObjectWriterwhich fully support reconfiguration as new instances are constructed.This method will be removed in Jackson 3.0 due to unsafe usage. Configure using
MapperBuilder.disable(SerializationFeature...). -
isEnabled
Method for checking whether given deserialization-specific feature is enabled. -
configure
Method for changing state of an on/off deserialization feature for this object mapper.Note: Changing the configuration of this
ObjectMapperinstance after its first use (read & write) is not safe and should not be attempted. Instead, usewith()andwithout()methods ofObjectReader/ObjectWriterwhich fully support reconfiguration as new instances are constructed.This method will be removed in Jackson 3.0 due to unsafe usage. Configure using
MapperBuilder.configure(DeserializationFeature, boolean). -
enable
Method for enabling specifiedDeserializationConfigfeatures. Modifies and returns this instance; no new object is created.Note: Changing the configuration of this
ObjectMapperinstance after its first use (read & write) is not safe and should not be attempted. Instead, usewith()andwithout()methods ofObjectReader/ObjectWriterwhich fully support reconfiguration as new instances are constructed.This method will be removed in Jackson 3.0 due to unsafe usage. Configure using
MapperBuilder.enable(DeserializationFeature...). -
enable
Method for enabling specifiedDeserializationConfigfeatures. Modifies and returns this instance; no new object is created.Note: Changing the configuration of this
ObjectMapperinstance after its first use (read & write) is not safe and should not be attempted. Instead, usewith()andwithout()methods ofObjectReader/ObjectWriterwhich fully support reconfiguration as new instances are constructed.This method will be removed in Jackson 3.0 due to unsafe usage. Configure using
MapperBuilder.enable(DeserializationFeature...). -
disable
Method for disabling specifiedDeserializationConfigfeatures. Modifies and returns this instance; no new object is created.Note: Changing the configuration of this
ObjectMapperinstance after its first use (read & write) is not safe and should not be attempted. Instead, usewith()andwithout()methods ofObjectReader/ObjectWriterwhich fully support reconfiguration as new instances are constructed.This method will be removed in Jackson 3.0 due to unsafe usage. Configure using
MapperBuilder.disable(DeserializationFeature...)instead. -
disable
Method for disabling specifiedDeserializationConfigfeatures. Modifies and returns this instance; no new object is created.Note: Changing the configuration of this
ObjectMapperinstance after its first use (read & write) is not safe and should not be attempted. Instead, usewith()andwithout()methods ofObjectReader/ObjectWriterwhich fully support reconfiguration as new instances are constructed.This method will be removed in Jackson 3.0 due to unsafe usage. Configure using
MapperBuilder.disable(DeserializationFeature...)instead. -
configure
Method for changing state of an on/off datatype-specific feature for this object mapper.Note: Changing the configuration of this
ObjectMapperinstance after its first use (read & write) is not safe and should not be attempted. Instead, usewith()andwithout()methods ofObjectReader/ObjectWriterwhich fully support reconfiguration as new instances are constructed.This method will be removed in Jackson 3.0 due to unsafe usage. Configure using
MapperBuilder.configure(DatatypeFeature, boolean)instead. -
isEnabled
-
configure
Method for changing state of specifiedJsonParser.Features for parser instances this object mapper creates.Note that this is equivalent to directly calling same method on
getFactory().WARNING: since this method directly modifies state of underlying
JsonFactory, it will change observed configuration byObjectReaders as well -- to avoid this, useObjectReader.with(JsonParser.Feature)instead.Also, this method will be removed in Jackson 3.0 due to unsafe usage and replaced by
MapperBuilder.configure(JsonParser.Feature, boolean). -
enable
Method for enabling specifiedJsonParser.Features for parser instances this object mapper creates.Note that this is equivalent to directly calling same method on
getFactory().WARNING: since this method directly modifies state of underlying
JsonFactory, it will change observed configuration byObjectReaders as well -- to avoid this, useObjectReader.with(JsonParser.Feature)instead.Also, this method will be removed in Jackson 3.0 due to unsafe usage and replaced by
MapperBuilder.enable(JsonParser.Feature...).- Since:
- 2.5
-
disable
Method for disabling specifiedJsonParser.Features for parser instances this object mapper creates.Note that this is equivalent to directly calling same method on
getFactory().WARNING: since this method directly modifies state of underlying
JsonFactory, it will change observed configuration byObjectReaders as well -- to avoid this, useObjectReader.without(JsonParser.Feature)instead.Also, this method will be removed in Jackson 3.0 due to unsafe usage and replaced by
MapperBuilder.disable(JsonParser.Feature...).- Since:
- 2.5
-
isEnabled
-
configure
Method for changing state of an on/offJsonGeneratorfeature for generator instances this object mapper creates.Note that this is equivalent to directly calling same method on
getFactory().WARNING: since this method directly modifies state of underlying
JsonFactory, it will change observed configuration byObjectWriters as well -- to avoid this, useObjectWriter.with(JsonGenerator.Feature)instead.This method will be removed in Jackson 3.0 due to unsafe usage. Configure using
MapperBuilder.configure(JsonGenerator.Feature, boolean)instead. -
enable
Method for enabling specifiedJsonGenerator.Features for parser instances this object mapper creates.Note that this is equivalent to directly calling same method on
getFactory().WARNING: since this method directly modifies state of underlying
JsonFactory, it will change observed configuration byObjectWriters as well -- to avoid this, useObjectWriter.with(JsonGenerator.Feature)instead.This method will be removed in Jackson 3.0 due to unsafe usage. Configure using
MapperBuilder.enable(JsonGenerator.Feature...)instead.- Since:
- 2.5
-
disable
Method for disabling specifiedJsonGenerator.Features for parser instances this object mapper creates.Note that this is equivalent to directly calling same method on
getFactory().WARNING: since this method directly modifies state of underlying
JsonFactory, it will change observed configuration byObjectWriters as well -- to avoid this, useObjectWriter.without(JsonGenerator.Feature)instead.This method will be removed in Jackson 3.0 due to unsafe usage. Configure using
MapperBuilder.disable(JsonGenerator.Feature...)instead.- Since:
- 2.5
-
isEnabled
Convenience method, equivalent to:getFactory().isEnabled(f);
-
isEnabled
- Since:
- 2.10
-
isEnabled
- Since:
- 2.10
-
readValue
public <T> T readValue(JsonParser p, Class<T> valueType) throws IOException, StreamReadException, DatabindException 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 (likeBoolean).Note: this method should NOT be used if the result type is a container (
CollectionorMap. The reason is that due to type erasure, key and value types cannot be introspected when using this method.- Specified by:
readValuein classObjectCodec- Type Parameters:
T- Nominal parameter for target type- Parameters:
p- Parser to use for decoding content to bindvalueType- Java value type to bind content to- Returns:
- Value deserialized
- Throws:
IOException- if a low-level I/O problem (unexpected end-of-input, network error) occurs (passed through as-is without additional wrapping -- note that this is one case whereDeserializationFeature.WRAP_EXCEPTIONSdoes NOT result in wrapping of exception even if enabled)StreamReadException- if underlying input contains invalid content of typeJsonParsersupports (JSON for default case)DatabindException- if the input JSON structure does not match structure expected for result type (or has other mismatch issues)
-
readValue
public <T> T readValue(JsonParser p, TypeReference<T> valueTypeRef) throws IOException, StreamReadException, DatabindException Method to deserialize JSON content into a Java type, reference to which is passed as argument. Type is passed using so-called "super type token" (see ) and specifically needs to be used if the root type is a parameterized (generic) container type.- Specified by:
readValuein classObjectCodec- Type Parameters:
T- Nominal parameter for target type- Parameters:
p- Parser to use for decoding content to bindvalueTypeRef- Java value type to bind content to- Returns:
- Value deserialized
- Throws:
IOException- if a low-level I/O problem (unexpected end-of-input, network error) occurs (passed through as-is without additional wrapping -- note that this is one case whereDeserializationFeature.WRAP_EXCEPTIONSdoes NOT result in wrapping of exception even if enabled)StreamReadException- if underlying input contains invalid content of typeJsonParsersupports (JSON for default case)DatabindException- if the input JSON structure does not match structure expected for result type (or has other mismatch issues)
-
readValue
public final <T> T readValue(JsonParser p, ResolvedType valueType) throws IOException, StreamReadException, DatabindException Method to deserialize JSON content into a Java type, reference to which is passed as argument. Type is passed using Jackson specific type; instance of which can be constructed usingTypeFactory.- Specified by:
readValuein classObjectCodec- Type Parameters:
T- Nominal parameter for target type- Parameters:
p- Parser to use for decoding content to bindvalueType- Java value type to bind content to- Returns:
- Value deserialized
- Throws:
IOException- if a low-level I/O problem (unexpected end-of-input, network error) occurs (passed through as-is without additional wrapping -- note that this is one case whereDeserializationFeature.WRAP_EXCEPTIONSdoes NOT result in wrapping of exception even if enabled)StreamReadException- if underlying input contains invalid content of typeJsonParsersupports (JSON for default case)DatabindException- if the input JSON structure does not match structure expected for result type (or has other mismatch issues)
-
readValue
public <T> T readValue(JsonParser p, JavaType valueType) throws IOException, StreamReadException, DatabindException Type-safe overloaded method, basically alias forreadValue(JsonParser, Class).- Throws:
IOException- if a low-level I/O problem (unexpected end-of-input, network error) occurs (passed through as-is without additional wrapping -- note that this is one case whereDeserializationFeature.WRAP_EXCEPTIONSdoes NOT result in wrapping of exception even if enabled)StreamReadException- if underlying input contains invalid content of typeJsonParsersupports (JSON for default case)DatabindException- if the input JSON structure does not match structure expected for result type (or has other mismatch issues)
-
readTree
Method to deserialize JSON content as a treeJsonNode. ReturnsJsonNodethat represents the root of the resulting tree, if there was content to read, ornullif no more content is accessible via passedJsonParser.NOTE! Behavior with end-of-input (no more content) differs between this
readTreemethod, and all other methods that take input source: latter will return "missing node", NOTnull- Specified by:
readTreein classObjectCodec- Returns:
- a
JsonNode, if valid JSON content found; null if input has no content to bind -- note, however, that if JSONnulltoken is found, it will be represented as a non-nullJsonNode(one that returnstrueforJsonNode.isNull() - Throws:
IOException- if a low-level I/O problem (unexpected end-of-input, network error) occurs (passed through as-is without additional wrapping -- note that this is one case whereDeserializationFeature.WRAP_EXCEPTIONSdoes NOT result in wrapping of exception even if enabled)StreamReadException- if underlying input contains invalid content of typeJsonParsersupports (JSON for default case)
-
readValues
Convenience method, equivalent in function to:readerFor(valueType).readValues(p);
Method for reading sequence of Objects from parser stream. Sequence can be either root-level "unwrapped" sequence (without surrounding JSON array), or a sequence contained in a JSON Array. In either case
JsonParserMUST point to the first token of the first element, OR not point to any token (in which case it is advanced to the next token). This means, specifically, that for wrapped sequences, parser MUST NOT point to the surroundingSTART_ARRAY(one that contains values to read) but rather to the token following it which is the first token of the first value to read.Note that
ObjectReaderhas more complete set of variants.- Specified by:
readValuesin classObjectCodec- Type Parameters:
T- Nominal parameter for target type- Parameters:
p- Parser to use for decoding content to bindvalueType- Java value type to bind content to- Returns:
- Iterator for incrementally deserializing values
- Throws:
IOException- for low-level read issues, orJsonParseExceptionfor decoding problems
-
readValues
Convenience method, equivalent in function to:readerFor(valueType).readValues(p);
Type-safe overload of
readValues(JsonParser, ResolvedType).- Throws:
IOException
-
readValues
Convenience method, equivalent in function to:readerFor(valueType).readValues(p);
Type-safe overload of
readValues(JsonParser, ResolvedType).- Specified by:
readValuesin classObjectCodec- Type Parameters:
T- Nominal parameter for target type- Parameters:
p- Parser to use for decoding content to bindvalueType- Java value type to bind content to- Returns:
- Iterator for incrementally deserializing values
- Throws:
IOException- for low-level read issues, orJsonParseExceptionfor decoding problems
-
readValues
public <T> MappingIterator<T> readValues(JsonParser p, TypeReference<T> valueTypeRef) throws IOException Method for reading sequence of Objects from parser stream.- Specified by:
readValuesin classObjectCodec- Type Parameters:
T- Nominal parameter for target type- Parameters:
p- Parser to use for decoding content to bindvalueTypeRef- Java value type to bind content to- Returns:
- Iterator for incrementally deserializing values
- Throws:
IOException- for low-level read issues, orJsonParseExceptionfor decoding problems
-
readTree
Method to deserialize JSON content as tree expressed using set ofJsonNodeinstances. Returns root of the resulting tree (where root can consist of just a single node if the current event is a value event, not container).If a low-level I/O problem (missing input, network error) occurs, a
IOExceptionwill be thrown. If a parsing problem occurs (invalid JSON),StreamReadExceptionwill be thrown. If no content is found from input (end-of-input), Javanullwill be returned.- Parameters:
in- Input stream used to read JSON content for building the JSON tree.- Returns:
- a
JsonNode, if valid JSON content found; null if input has no content to bind -- note, however, that if JSONnulltoken is found, it will be represented as a non-nullJsonNode(one that returnstrueforJsonNode.isNull() - Throws:
StreamReadException- if underlying input contains invalid content of typeJsonParsersupports (JSON for default case)IOException
-
readTree
Same asreadTree(InputStream)except content accessed through passed-inReader- Throws:
IOException
-
readTree
Same asreadTree(InputStream)except content read from passed-inString -
readTree
Same asreadTree(InputStream)except content read from passed-in byte array.- Throws:
IOException
-
readTree
Same asreadTree(InputStream)except content read from passed-in byte array.- Throws:
IOException
-
readTree
Same asreadTree(InputStream)except content read from passed-inFile.- Throws:
IOException
-
readTree
Same asreadTree(InputStream)except content read from passed-inURL.NOTE: handling of
URLis delegated toJsonFactory.createParser(java.net.URL)and usually simply callsURL.openStream(), meaning no special handling is done. If different HTTP connection options are needed you will need to createInputStreamseparately.- Throws:
IOException
-
writeValue
public void writeValue(JsonGenerator g, Object value) throws IOException, StreamWriteException, DatabindException Method that can be used to serialize any Java value as JSON output, using providedJsonGenerator.- Specified by:
writeValuein classObjectCodec- Parameters:
g- Generator to use for serializing valuevalue- Value to serialize- Throws:
IOException- for low-level write issues, orJsonGenerationExceptionfor decoding problemsStreamWriteExceptionDatabindException
-
writeTree
Description copied from class:ObjectCodecMethod for serializing JSON content from given Tree instance, using specified generator.- Specified by:
writeTreein classObjectCodec- Parameters:
g- Generator to use for serializing valuerootNode- Tree to serialize- Throws:
IOException- for low-level write issues, orJsonGenerationExceptionfor decoding problems
-
writeTree
Method to serialize given JSON Tree, using generator provided.- Throws:
IOException
-
createObjectNode
Note: return type is co-variant, as basic ObjectCodec abstraction cannot refer to concrete node types (as it's part of core package, whereas impls are part of mapper package)
- Specified by:
createObjectNodein classObjectCodec- Returns:
- Object node created
-
createArrayNode
Note: return type is co-variant, as basic ObjectCodec abstraction cannot refer to concrete node types (as it's part of core package, whereas impls are part of mapper package)
- Specified by:
createArrayNodein classObjectCodec- Returns:
- Array node created
-
missingNode
- Overrides:
missingNodein classTreeCodec- Returns:
- Node that represents "missing" node during traversal: something referenced but that does not exist in content model
-
nullNode
-
treeAsTokens
Method for constructing aJsonParserout of JSON tree representation.- Specified by:
treeAsTokensin classObjectCodec- Parameters:
n- Root node of the tree that resulting parser will read from- Returns:
- Parser constructed for traversing over contents of specified node
-
treeToValue
public <T> T treeToValue(TreeNode n, Class<T> valueType) throws IllegalArgumentException, JsonProcessingException Convenience conversion method that will bind data given JSON tree contains into specific value (usually bean) type.Functionally equivalent to:
objectMapper.convertValue(n, valueClass);
Note: inclusion of
throws JsonProcessingExceptionis not accidental since while there can be no input decoding problems, it is possible that content does not match target type: in such case variousDatabindExceptions are possible. In additionIllegalArgumentExceptionis possible in some cases, depending on whetherDeserializationFeature.WRAP_EXCEPTIONSis enabled or not.- Specified by:
treeToValuein classObjectCodec- Type Parameters:
T- Nominal parameter for target type- Parameters:
n- Tree to convertvalueType- Java target value type to convert content to- Returns:
- Converted value instance
- Throws:
JsonProcessingException- if structural conversion failsIllegalArgumentException
-
treeToValue
public <T> T treeToValue(TreeNode n, JavaType valueType) throws IllegalArgumentException, JsonProcessingException Same astreeToValue(TreeNode, Class)but target type specified using fully resolvedJavaType.- Throws:
IllegalArgumentExceptionJsonProcessingException- Since:
- 2.13
-
treeToValue
public <T> T treeToValue(TreeNode n, TypeReference<T> toValueTypeRef) throws IllegalArgumentException, JsonProcessingException Same astreeToValue(TreeNode, JavaType)but target type specified using fully resolvedTypeReference.- Throws:
IllegalArgumentExceptionJsonProcessingException- Since:
- 2.16
-
valueToTree
Method that is reverse oftreeToValue(com.fasterxml.jackson.core.TreeNode, java.lang.Class<T>): it will convert given Java value (usually bean) into its equivalent Tree modeJsonNoderepresentation. Functionally similar to serializing value into token stream and parsing that stream back as tree model node, but more efficient asTokenBufferis used to contain the intermediate representation instead of fully serialized contents.NOTE: while results are usually identical to that of serialization followed by deserialization, this is not always the case. In some cases serialization into intermediate representation will retain encapsulation of things like raw value (
RawValue) or basic node identity (JsonNode). If so, result is a valid tree, but values are not re-constructed through actual format representation. So if transformation requires actual materialization of encoded content, it will be necessary to do actual serialization.- Type Parameters:
T- Actual node type; usually either basicJsonNodeorObjectNode- Parameters:
fromValue- Java value to convert- Returns:
- (non-null) Root node of the resulting content tree: in case of
nullvalue node for whichJsonNode.isNull()returnstrue. - Throws:
IllegalArgumentException
-
canSerialize
Method that can be called to check whether mapper thinks it could serialize an instance of given Class. Check is done by checking whether a serializer can be found for the type.NOTE: since this method does NOT throw exceptions, but internal processing may, caller usually has little information as to why serialization would fail. If you want access to internal
Exception, callcanSerialize(Class, AtomicReference)instead.- Returns:
- True if mapper can find a serializer for instances of given class (potentially serializable), false otherwise (not serializable)
-
canSerialize
Method similar tocanSerialize(Class)but that can return actualThrowablethat was thrown when trying to construct serializer: this may be useful in figuring out what the actual problem is.- Since:
- 2.3
-
canDeserialize
Method that can be called to check whether mapper thinks it could deserialize an Object of given type. Check is done by checking whether a registered deserializer can be found or built for the type; if not (either by no mapping being found, or through anExceptionbeing thrown, false is returned.NOTE: in case an exception is thrown during course of trying co construct matching deserializer, it will be effectively swallowed. If you want access to that exception, call
canDeserialize(JavaType, AtomicReference)instead.- Returns:
- True if mapper can find a serializer for instances of given class (potentially serializable), false otherwise (not serializable)
-
canDeserialize
Method similar tocanDeserialize(JavaType)but that can return actualThrowablethat was thrown when trying to construct serializer: this may be useful in figuring out what the actual problem is.- Since:
- 2.3
-
readValue
public <T> T readValue(File src, Class<T> valueType) throws IOException, StreamReadException, DatabindException Method to deserialize JSON content from given file into given Java type.- Throws:
IOException- if a low-level I/O problem (unexpected end-of-input, network error) occurs (passed through as-is without additional wrapping -- note that this is one case whereDeserializationFeature.WRAP_EXCEPTIONSdoes NOT result in wrapping of exception even if enabled)StreamReadException- if underlying input contains invalid content of typeJsonParsersupports (JSON for default case)DatabindException- if the input JSON structure does not match structure expected for result type (or has other mismatch issues)
-
readValue
public <T> T readValue(File src, TypeReference<T> valueTypeRef) throws IOException, StreamReadException, DatabindException Method to deserialize JSON content from given file into given Java type.- Throws:
IOException- if a low-level I/O problem (unexpected end-of-input, network error) occurs (passed through as-is without additional wrapping -- note that this is one case whereDeserializationFeature.WRAP_EXCEPTIONSdoes NOT result in wrapping of exception even if enabled)StreamReadException- if underlying input contains invalid content of typeJsonParsersupports (JSON for default case)DatabindException- if the input JSON structure does not match structure expected for result type (or has other mismatch issues)
-
readValue
public <T> T readValue(File src, JavaType valueType) throws IOException, StreamReadException, DatabindException Method to deserialize JSON content from given file into given Java type.- Throws:
IOException- if a low-level I/O problem (unexpected end-of-input, network error) occurs (passed through as-is without additional wrapping -- note that this is one case whereDeserializationFeature.WRAP_EXCEPTIONSdoes NOT result in wrapping of exception even if enabled)StreamReadException- if underlying input contains invalid content of typeJsonParsersupports (JSON for default case)DatabindException- if the input JSON structure does not match structure expected for result type (or has other mismatch issues)
-
readValue
public <T> T readValue(URL src, Class<T> valueType) throws IOException, StreamReadException, DatabindException Method to deserialize JSON content from given resource into given Java type.NOTE: handling of
URLis delegated toJsonFactory.createParser(java.net.URL)and usually simply callsURL.openStream(), meaning no special handling is done. If different HTTP connection options are needed you will need to createInputStreamseparately.- Throws:
IOException- if a low-level I/O problem (unexpected end-of-input, network error) occurs (passed through as-is without additional wrapping -- note that this is one case whereDeserializationFeature.WRAP_EXCEPTIONSdoes NOT result in wrapping of exception even if enabled)StreamReadException- if underlying input contains invalid content of typeJsonParsersupports (JSON for default case)DatabindException- if the input JSON structure does not match structure expected for result type (or has other mismatch issues)
-
readValue
public <T> T readValue(URL src, TypeReference<T> valueTypeRef) throws IOException, StreamReadException, DatabindException Same asreadValue(java.net.URL, Class)except that target specified byTypeReference. -
readValue
public <T> T readValue(URL src, JavaType valueType) throws IOException, StreamReadException, DatabindException Same asreadValue(java.net.URL, Class)except that target specified byJavaType. -
readValue
public <T> T readValue(String content, Class<T> valueType) throws JsonProcessingException, JsonMappingException Method to deserialize JSON content from given JSON content String.- Throws:
StreamReadException- if underlying input contains invalid content of typeJsonParsersupports (JSON for default case)DatabindException- if the input JSON structure does not match structure expected for result type (or has other mismatch issues)JsonProcessingExceptionJsonMappingException
-
readValue
public <T> T readValue(String content, TypeReference<T> valueTypeRef) throws JsonProcessingException, JsonMappingException Method to deserialize JSON content from given JSON content String.- Throws:
StreamReadException- if underlying input contains invalid content of typeJsonParsersupports (JSON for default case)DatabindException- if the input JSON structure does not match structure expected for result type (or has other mismatch issues)JsonProcessingExceptionJsonMappingException
-
readValue
public <T> T readValue(String content, JavaType valueType) throws JsonProcessingException, JsonMappingException Method to deserialize JSON content from given JSON content String.- Throws:
StreamReadException- if underlying input contains invalid content of typeJsonParsersupports (JSON for default case)DatabindException- if the input JSON structure does not match structure expected for result type (or has other mismatch issues)JsonProcessingExceptionJsonMappingException
-
readValue
public <T> T readValue(Reader src, Class<T> valueType) throws IOException, StreamReadException, DatabindException -
readValue
public <T> T readValue(Reader src, TypeReference<T> valueTypeRef) throws IOException, StreamReadException, DatabindException -
readValue
public <T> T readValue(Reader src, JavaType valueType) throws IOException, StreamReadException, DatabindException -
readValue
public <T> T readValue(InputStream src, Class<T> valueType) throws IOException, StreamReadException, DatabindException -
readValue
public <T> T readValue(InputStream src, TypeReference<T> valueTypeRef) throws IOException, StreamReadException, DatabindException -
readValue
public <T> T readValue(InputStream src, JavaType valueType) throws IOException, StreamReadException, DatabindException -
readValue
public <T> T readValue(byte[] src, Class<T> valueType) throws IOException, StreamReadException, DatabindException -
readValue
public <T> T readValue(byte[] src, int offset, int len, Class<T> valueType) throws IOException, StreamReadException, DatabindException -
readValue
public <T> T readValue(byte[] src, TypeReference<T> valueTypeRef) throws IOException, StreamReadException, DatabindException -
readValue
public <T> T readValue(byte[] src, int offset, int len, TypeReference<T> valueTypeRef) throws IOException, StreamReadException, DatabindException -
readValue
public <T> T readValue(byte[] src, JavaType valueType) throws IOException, StreamReadException, DatabindException -
readValue
public <T> T readValue(byte[] src, int offset, int len, JavaType valueType) throws IOException, StreamReadException, DatabindException -
readValue
- Throws:
IOException
-
readValue
- Throws:
IOException
-
writeValue
public void writeValue(File resultFile, Object value) throws IOException, StreamWriteException, DatabindException Method that can be used to serialize any Java value as JSON output, written to File provided. -
writeValue
public void writeValue(OutputStream out, Object value) throws IOException, StreamWriteException, DatabindException Method that can be used to serialize any Java value as JSON output, using output stream provided (using encodingJsonEncoding.UTF8).Note: method does not close the underlying stream explicitly here; however,
JsonFactorythis mapper uses may choose to close the stream depending on its settings (by default, it will try to close it whenJsonGeneratorwe construct is closed). -
writeValue
- Throws:
IOException- Since:
- 2.8
-
writeValue
public void writeValue(Writer w, Object value) throws IOException, StreamWriteException, DatabindException Method that can be used to serialize any Java value as JSON output, using Writer provided.Note: method does not close the underlying stream explicitly here; however,
JsonFactorythis mapper uses may choose to close the stream depending on its settings (by default, it will try to close it whenJsonGeneratorwe construct is closed). -
writeValueAsString
Method that can be used to serialize any Java value as a String. Functionally equivalent to callingwriteValue(Writer,Object)withStringWriterand constructing String, but more efficient.Note: prior to version 2.1, throws clause included
IOException; 2.1 removed it.- Throws:
JsonProcessingException
-
writeValueAsBytes
Method that can be used to serialize any Java value as a byte array. Functionally equivalent to callingwriteValue(Writer,Object)withByteArrayOutputStreamand getting bytes, but more efficient. Encoding used will be UTF-8.Note: prior to version 2.1, throws clause included
IOException; 2.1 removed it.- Throws:
JsonProcessingException
-
writer
Convenience method for constructingObjectWriterwith default settings. -
writer
Factory method for constructingObjectWriterwith specified feature enabled (compared to settings that this mapper instance has). -
writer
Factory method for constructingObjectWriterwith specified features enabled (compared to settings that this mapper instance has). -
writer
Factory method for constructingObjectWriterthat will serialize objects using specifiedDateFormat; or, if null passed, using timestamp (64-bit number. -
writerWithView
Factory method for constructingObjectWriterthat will serialize objects using specified JSON View (filter). -
writerFor
Factory method for constructingObjectWriterthat will serialize objects using specified root type, instead of actual runtime type of value. Type must be a super-type of runtime type.Main reason for using this method is performance, as writer is able to pre-fetch serializer to use before write, and if writer is used more than once this avoids addition per-value serializer lookups.
- Since:
- 2.5
-
writerFor
Factory method for constructingObjectWriterthat will serialize objects using specified root type, instead of actual runtime type of value. Type must be a super-type of runtime type.Main reason for using this method is performance, as writer is able to pre-fetch serializer to use before write, and if writer is used more than once this avoids addition per-value serializer lookups.
- Since:
- 2.5
-
writerFor
Factory method for constructingObjectWriterthat will serialize objects using specified root type, instead of actual runtime type of value. Type must be a super-type of runtime type.Main reason for using this method is performance, as writer is able to pre-fetch serializer to use before write, and if writer is used more than once this avoids addition per-value serializer lookups.
- Since:
- 2.5
-
writer
Factory method for constructingObjectWriterthat will serialize objects using specified pretty printer for indentation (or if null, no pretty printer) -
writerWithDefaultPrettyPrinter
Factory method for constructingObjectWriterthat will serialize objects using the default pretty printer for indentation -
writer
Factory method for constructingObjectWriterthat will serialize objects using specified filter provider. -
writer
Factory method for constructingObjectWriterthat will pass specific schema object toJsonGeneratorused for writing content.- Parameters:
schema- Schema to pass to generator
-
writer
Factory method for constructingObjectWriterthat will use specified Base64 encoding variant for Base64-encoded binary data.- Since:
- 2.1
-
writer
Factory method for constructingObjectReaderthat will use specified character escaping details for output.- Since:
- 2.3
-
writer
Factory method for constructingObjectWriterthat will use specified default attributes.- Since:
- 2.3
-
writerWithType
Deprecated.Since 2.5, usewriterFor(Class)instead -
writerWithType
Deprecated.Since 2.5, usewriterFor(TypeReference)instead -
writerWithType
Deprecated.Since 2.5, usewriterFor(JavaType)instead -
reader
Factory method for constructingObjectReaderwith default settings. Note that the resulting instance is NOT usable as is, without defining expected value type. -
reader
Factory method for constructingObjectReaderwith specified feature enabled (compared to settings that this mapper instance has). Note that the resulting instance is NOT usable as is, without defining expected value type. -
reader
Factory method for constructingObjectReaderwith specified features enabled (compared to settings that this mapper instance has). Note that the resulting instance is NOT usable as is, without defining expected value type. -
readerForUpdating
Factory method for constructingObjectReaderthat will update given Object (usually Bean, but can be a Collection or Map as well, but NOT an array) with JSON data. Deserialization occurs normally except that the root-level value in JSON is not used for instantiating a new object; instead give updateable object is used as root. Runtime type of value object is used for locating deserializer, unless overridden by other factory methods ofObjectReader -
readerFor
Factory method for constructingObjectReaderthat will read or update instances of specified type- Since:
- 2.6
-
readerFor
Factory method for constructingObjectReaderthat will read or update instances of specified type- Since:
- 2.6
-
readerFor
Factory method for constructingObjectReaderthat will read or update instances of specified type- Since:
- 2.6
-
readerForArrayOf
Factory method for constructingObjectReaderthat will read values of a typeList<type>. Functionally same as:readerFor(type[].class);- Since:
- 2.11
-
readerForListOf
Factory method for constructingObjectReaderthat will read or update instances of a typeList<type>. Functionally same as:readerFor(new TypeReference<List<type>>() { });- Since:
- 2.11
-
readerForMapOf
Factory method for constructingObjectReaderthat will read or update instances of a typeMap<String, type>Functionally same as:readerFor(new TypeReference<Map<String, type>>() { });- Since:
- 2.11
-
reader
Factory method for constructingObjectReaderthat will use specifiedJsonNodeFactoryfor constructing JSON trees. -
reader
Factory method for constructingObjectReaderthat will pass specific schema object toJsonParserused for reading content.- Parameters:
schema- Schema to pass to parser
-
reader
Factory method for constructingObjectReaderthat will use specified injectable values.- Parameters:
injectableValues- Injectable values to use
-
readerWithView
Factory method for constructingObjectReaderthat will deserialize objects using specified JSON View (filter). -
reader
Factory method for constructingObjectReaderthat will use specified Base64 encoding variant for Base64-encoded binary data.- Since:
- 2.1
-
reader
Factory method for constructingObjectReaderthat will use specified default attributes.- Since:
- 2.3
-
reader
Deprecated.Since 2.5, usereaderFor(JavaType)instead -
reader
Deprecated.Since 2.5, usereaderFor(Class)instead -
reader
Deprecated.Since 2.5, usereaderFor(TypeReference)instead -
convertValue
Convenience method for doing two-step conversion from given value, into instance of given value type, by writing value into temporary buffer and reading from the buffer into specified target type.This method is functionally similar to first serializing given value into JSON, and then binding JSON data into value of given type, but should be more efficient since full serialization does not (need to) occur. However, same converters (serializers, deserializers) will be used as for data binding, meaning same object mapper configuration works.
Note that behavior changed slightly between Jackson 2.9 and 2.10 so that whereas earlier some optimizations were used to avoid write/read cycle in case input was of target type, from 2.10 onwards full processing is always performed. See databind#2220 for full details of the change.
Further note that it is possible that in some cases behavior does differ from full serialize-then-deserialize cycle: in most case differences are unintentional (that is, flaws to fix) and should be reported, but the behavior is not guaranteed to be 100% the same: the goal is to allow efficient value conversions for structurally compatible Objects, according to standard Jackson configuration.
Finally, this functionality is not designed to support "advanced" use cases, such as conversion of polymorphic values, or cases where Object Identity is used.
- Throws:
IllegalArgumentException- If conversion fails due to incompatible type; if so, root cause will contain underlying checked exception data binding functionality threw
-
convertValue
public <T> T convertValue(Object fromValue, TypeReference<T> toValueTypeRef) throws IllegalArgumentException - Throws:
IllegalArgumentException
-
convertValue
- Throws:
IllegalArgumentException
-
updateValue
Convenience method similar toconvertValue(Object, JavaType)but one in whichImplementation is approximately as follows:
- Serialize `updateWithValue` into
TokenBuffer - Construct
ObjectReaderwith `valueToUpdate` (usingreaderForUpdating(Object)) - Construct
JsonParser(usingTokenBuffer.asParser()) - Update using
ObjectReader.readValue(JsonParser). - Return `valueToUpdate`
Note that update is "shallow" in that only first level of properties (or, immediate contents of container to update) are modified, unless properties themselves indicate that merging should be applied for contents. Such merging can be specified using annotations (see
JsonMerge) as well as using "config overrides" (seeconfigOverride(Class)andsetDefaultMergeable(Boolean)).- Parameters:
valueToUpdate- Object to updateoverrides- Object to conceptually serialize and merge into value to update; can be thought of as a provider for overrides to apply.- Returns:
- Either the first argument (`valueToUpdate`), if it is mutable; or a result of creating new instance that is result of "merging" values (for example, "updating" a Java array will create a new array)
- Throws:
JsonMappingException- if there are structural incompatibilities that prevent update.- Since:
- 2.9
- Serialize `updateWithValue` into
-
generateJsonSchema
Deprecated.Since 2.6 use external JSON Schema generator (jackson-module-jsonSchema) (which under the hood callsacceptJsonFormatVisitor(JavaType, JsonFormatVisitorWrapper))Generate Json-schema instance for specified class.- Parameters:
t- The class to generate schema for- Returns:
- Constructed JSON schema.
- Throws:
JsonMappingException
-
acceptJsonFormatVisitor
public void acceptJsonFormatVisitor(Class<?> type, JsonFormatVisitorWrapper visitor) throws JsonMappingException Method for visiting type hierarchy for given type, using specified visitor.This method can be used for things like generating JSON Schema instance for specified type.
- Parameters:
type- Type to generate schema for (possibly with generic signature)- Throws:
JsonMappingException- Since:
- 2.1
-
acceptJsonFormatVisitor
public void acceptJsonFormatVisitor(JavaType type, JsonFormatVisitorWrapper visitor) throws JsonMappingException Method for visiting type hierarchy for given type, using specified visitor. Visitation usesSerializerhierarchy and related propertiesThis method can be used for things like generating JSON Schema instance for specified type.
- Parameters:
type- Type to generate schema for (possibly with generic signature)- Throws:
JsonMappingException- Since:
- 2.1
-
addMixIn(Class, Class).