Class ObjectMapper
- java.lang.Object
-
- com.fasterxml.jackson.core.TreeCodec
-
- com.fasterxml.jackson.core.ObjectCodec
-
- com.fasterxml.jackson.databind.ObjectMapper
-
- All Implemented Interfaces:
com.fasterxml.jackson.core.Versioned,Serializable
- Direct Known Subclasses:
JsonMapper
public class ObjectMapper extends com.fasterxml.jackson.core.ObjectCodec implements com.fasterxml.jackson.core.Versioned, Serializable
ObjectMapper provides functionality for reading and writing JSON, either to and from basic POJOs (Plain Old Java Objects), or to and from a general-purpose JSON Tree Model (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.ObjectMapperalso acts as a factory for more advancedObjectReaderandObjectWriterclasses. Mapper (andObjectReaders,ObjectWriters it constructs) will use instances ofJsonParserandJsonGeneratorfor 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 viaObjectReaderandObjectWriter: specifically, reading/writing of longer sequences of values is only available throughObjectReader.readValues(InputStream)andObjectWriter.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 aJsonPointerexpression: 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 viaObjectCodecis, however, usually only for cases where dependency toObjectMapperis 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 "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 customTypeResolverBuilderimplementation to limit possible types to instantiate, (usingsetDefaultTyping(com.fasterxml.jackson.databind.jsontype.TypeResolverBuilder<?>)).- See Also:
- Serialized Form
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static classObjectMapper.DefaultTypeResolverBuilderCustomizedTypeResolverBuilderthat provides type resolver builders used with so-called "default typing" (seeactivateDefaultTyping(PolymorphicTypeValidator)for details).static classObjectMapper.DefaultTypingEnumeration used withactivateDefaultTyping(PolymorphicTypeValidator)to specify what kind of types (classes) default typing should be used for.
-
Field Summary
Fields Modifier and Type Field Description protected ConfigOverrides_configOverridesCurrently active per-type configuration overrides, accessed by declared type of property.protected DeserializationConfig_deserializationConfigConfiguration object that defines basic global settings for the serialization processprotected DefaultDeserializationContext_deserializationContextBlueprint context object; stored here to allow custom sub-classes.protected InjectableValues_injectableValuesProvider for values to inject in deserialized POJOs.protected com.fasterxml.jackson.core.JsonFactory_jsonFactoryFactory used to createJsonParserandJsonGeneratorinstances as necessary.protected SimpleMixInResolver_mixInsMapping that defines how to apply mix-in annotations: key is the type to received additional annotations, and value is the type that has annotations to "mix in".protected Set<Object>_registeredModuleTypesSet of module types (as perModule.getTypeId()that have been registered; kept track of iffMapperFeature.IGNORE_DUPLICATE_MODULE_REGISTRATIONSis enabled, so that duplicate registration calls can be ignored (to avoid adding same handlers multiple times, mostly).protected ConcurrentHashMap<JavaType,JsonDeserializer<Object>>_rootDeserializersWe will use a separate main-level Map for keeping track of root-level deserializers.protected SerializationConfig_serializationConfigConfiguration object that defines basic global settings for the serialization processprotected SerializerFactory_serializerFactorySerializer factory used for constructing serializers.protected DefaultSerializerProvider_serializerProviderObject that manages access to serializers used for serialization, including caching.protected SubtypeResolver_subtypeResolverThing used for registering sub-types, resolving them to super/sub-types as needed.protected TypeFactory_typeFactorySpecific factory used for creatingJavaTypeinstances; needed to allow modules to add more custom type handling (mostly to support types of non-Java JVM languages)protected static AnnotationIntrospectorDEFAULT_ANNOTATION_INTROSPECTORprotected static BaseSettingsDEFAULT_BASEBase settings contain defaults used for allObjectMapperinstances.
-
Constructor Summary
Constructors Modifier Constructor Description ObjectMapper()Default constructor, which will construct the defaultJsonFactoryas necessary, useSerializerProvideras itsSerializerProvider, andBeanSerializerFactoryas itsSerializerFactory.ObjectMapper(com.fasterxml.jackson.core.JsonFactory jf)Constructs instance that uses specifiedJsonFactoryfor constructing necessaryJsonParsers and/orJsonGenerators.ObjectMapper(com.fasterxml.jackson.core.JsonFactory jf, DefaultSerializerProvider sp, DefaultDeserializationContext dc)Constructs instance that uses specifiedJsonFactoryfor constructing necessaryJsonParsers and/orJsonGenerators, and uses given providers for accessing serializers and deserializers.protectedObjectMapper(ObjectMapper src)Copy-constructor, mostly used to supportcopy().
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Deprecated Methods Modifier and Type Method Description protected void_assertNotNull(String paramName, Object src)protected void_checkInvalidCopy(Class<?> exp)protected void_configAndWriteValue(com.fasterxml.jackson.core.JsonGenerator g, Object value)Method called to configure the generator as necessary and then call write functionalityprotected TypeResolverBuilder<?>_constructDefaultTypeResolverBuilder(ObjectMapper.DefaultTyping applicability, PolymorphicTypeValidator ptv)Overridable factory method, separate to allow format-specific mappers (and specifically XML-backed one, currently) to offer customTypeResolverBuildersubtypes.protected Object_convert(Object fromValue, JavaType toValueType)Actual conversion implementation: instead of using existing read and write methods, much of code is inlined.protected JsonDeserializer<Object>_findRootDeserializer(DeserializationContext ctxt, JavaType valueType)Method called to locate deserializer for the passed root-level value.protected com.fasterxml.jackson.core.JsonToken_initForReading(com.fasterxml.jackson.core.JsonParser p)Deprecated.protected com.fasterxml.jackson.core.JsonToken_initForReading(com.fasterxml.jackson.core.JsonParser p, JavaType targetType)Method called to ensure that given parser is ready for reading content for data binding.protected ObjectReader_newReader(DeserializationConfig config)Factory method sub-classes must override, to produceObjectReaderinstances of proper sub-typeprotected ObjectReader_newReader(DeserializationConfig config, JavaType valueType, Object valueToUpdate, com.fasterxml.jackson.core.FormatSchema schema, InjectableValues injectableValues)Factory method sub-classes must override, to produceObjectReaderinstances of proper sub-typeprotected ObjectWriter_newWriter(SerializationConfig config)Factory method sub-classes must override, to produceObjectWriterinstances of proper sub-typeprotected ObjectWriter_newWriter(SerializationConfig config, com.fasterxml.jackson.core.FormatSchema schema)Factory method sub-classes must override, to produceObjectWriterinstances of proper sub-typeprotected ObjectWriter_newWriter(SerializationConfig config, JavaType rootType, com.fasterxml.jackson.core.PrettyPrinter pp)Factory method sub-classes must override, to produceObjectWriterinstances of proper sub-typeprotected Object_readMapAndClose(com.fasterxml.jackson.core.JsonParser p0, JavaType valueType)protected JsonNode_readTreeAndClose(com.fasterxml.jackson.core.JsonParser p0)Similar to_readMapAndClose(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.databind.JavaType)but specialized forJsonNodereading.protected Object_readValue(DeserializationConfig cfg, com.fasterxml.jackson.core.JsonParser p, JavaType valueType)Actual implementation of value reading+binding operation.protected DefaultSerializerProvider_serializerProvider(SerializationConfig config)Overridable helper method used for constructingSerializerProviderto use for serialization.protected Object_unwrapAndDeserialize(com.fasterxml.jackson.core.JsonParser p, DeserializationContext ctxt, DeserializationConfig config, JavaType rootType, JsonDeserializer<Object> deser)protected void_verifyNoTrailingTokens(com.fasterxml.jackson.core.JsonParser p, DeserializationContext ctxt, JavaType bindType)protected void_verifySchemaType(com.fasterxml.jackson.core.FormatSchema schema)voidacceptJsonFormatVisitor(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.ObjectMapperactivateDefaultTyping(PolymorphicTypeValidator ptv)Convenience method that is equivalent to callingObjectMapperactivateDefaultTyping(PolymorphicTypeValidator ptv, ObjectMapper.DefaultTyping applicability)Convenience method that is equivalent to callingObjectMapperactivateDefaultTyping(PolymorphicTypeValidator ptv, ObjectMapper.DefaultTyping applicability, com.fasterxml.jackson.annotation.JsonTypeInfo.As includeAs)Method for enabling automatic inclusion of type information, needed for proper deserialization of polymorphic types (unless types have been annotated withJsonTypeInfo).ObjectMapperactivateDefaultTypingAsProperty(PolymorphicTypeValidator ptv, ObjectMapper.DefaultTyping applicability, String propertyName)Method for enabling automatic inclusion of type information -- 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)ObjectMapperaddHandler(DeserializationProblemHandler h)Method for adding specifiedDeserializationProblemHandlerto be used for handling specific problems during deserialization.ObjectMapperaddMixIn(Class<?> target, Class<?> mixinSource)Method to use for adding mix-in annotations to use for augmenting specified class or interface.voidaddMixInAnnotations(Class<?> target, Class<?> mixinSource)Deprecated.Since 2.5: replaced by a fluent form of the method;addMixIn(Class, Class).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.ObjectMapperclearProblemHandlers()Method for removing all registeredDeserializationProblemHandlers instances from this mapper.MutableConfigOverrideconfigOverride(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.ObjectMapperconfigure(com.fasterxml.jackson.core.JsonGenerator.Feature f, boolean state)Method for changing state of an on/offJsonGeneratorfeature for generator instances this object mapper creates.ObjectMapperconfigure(com.fasterxml.jackson.core.JsonParser.Feature f, boolean state)Method for changing state of specifiedJsonParser.Features for parser instances this object mapper creates.ObjectMapperconfigure(DeserializationFeature f, boolean state)Method for changing state of an on/off deserialization feature for this object mapper.ObjectMapperconfigure(MapperFeature f, boolean state)ObjectMapperconfigure(SerializationFeature f, boolean state)Method for changing state of an on/off serialization feature for this object mapper.JavaTypeconstructType(Type t)Convenience method for constructingJavaTypeout of given type (typicallyjava.lang.Class), but without explicit context.<T> TconvertValue(Object fromValue, com.fasterxml.jackson.core.type.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.ObjectMappercopy()Method for creating a newObjectMapperinstance that has same initial configuration as this instance.ArrayNodecreateArrayNode()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)protected DefaultDeserializationContextcreateDeserializationContext(com.fasterxml.jackson.core.JsonParser p, DeserializationConfig cfg)Internal helper method called to create an instance ofDeserializationContextfor deserializing a single root value.ObjectNodecreateObjectNode()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)ObjectMapperdeactivateDefaultTyping()Method for disabling automatic inclusion of type information; if so, only explicitly annotated types (ones withJsonTypeInfo) will have additional embedded type information.protected ClassIntrospectordefaultClassIntrospector()Overridable helper method used to construct defaultClassIntrospectorto use.ObjectMapperdisable(com.fasterxml.jackson.core.JsonGenerator.Feature... features)Method for disabling specifiedJsonGenerator.Features for parser instances this object mapper creates.ObjectMapperdisable(com.fasterxml.jackson.core.JsonParser.Feature... features)Method for disabling specifiedJsonParser.Features for parser instances this object mapper creates.ObjectMapperdisable(DeserializationFeature feature)Method for enabling specifiedDeserializationConfigfeatures.ObjectMapperdisable(DeserializationFeature first, DeserializationFeature... f)Method for enabling specifiedDeserializationConfigfeatures.ObjectMapperdisable(MapperFeature... f)ObjectMapperdisable(SerializationFeature f)Method for enabling specifiedDeserializationConfigfeatures.ObjectMapperdisable(SerializationFeature first, SerializationFeature... f)Method for enabling specifiedDeserializationConfigfeatures.ObjectMapperdisableDefaultTyping()Deprecated.Since 2.10 usedeactivateDefaultTyping()insteadObjectMapperenable(com.fasterxml.jackson.core.JsonGenerator.Feature... features)Method for enabling specifiedJsonGenerator.Features for parser instances this object mapper creates.ObjectMapperenable(com.fasterxml.jackson.core.JsonParser.Feature... features)Method for enabling specifiedJsonParser.Features for parser instances this object mapper creates.ObjectMapperenable(DeserializationFeature feature)Method for enabling specifiedDeserializationConfigfeatures.ObjectMapperenable(DeserializationFeature first, DeserializationFeature... f)Method for enabling specifiedDeserializationConfigfeatures.ObjectMapperenable(MapperFeature... f)ObjectMapperenable(SerializationFeature f)Method for enabling specifiedDeserializationConfigfeature.ObjectMapperenable(SerializationFeature first, SerializationFeature... f)Method for enabling specifiedDeserializationConfigfeatures.ObjectMapperenableDefaultTyping()Deprecated.Since 2.10 useactivateDefaultTyping(PolymorphicTypeValidator)insteadObjectMapperenableDefaultTyping(ObjectMapper.DefaultTyping dti)Deprecated.Since 2.10 useactivateDefaultTyping(PolymorphicTypeValidator,DefaultTyping)insteadObjectMapperenableDefaultTyping(ObjectMapper.DefaultTyping applicability, com.fasterxml.jackson.annotation.JsonTypeInfo.As includeAs)Deprecated.Since 2.10 useactivateDefaultTyping(PolymorphicTypeValidator,DefaultTyping,JsonTypeInfo.As)insteadObjectMapperenableDefaultTypingAsProperty(ObjectMapper.DefaultTyping applicability, String propertyName)Deprecated.Since 2.10 useactivateDefaultTypingAsProperty(PolymorphicTypeValidator,DefaultTyping,String)insteadObjectMapperfindAndRegisterModules()Convenience method that is functionally equivalent to:mapper.registerModules(mapper.findModules());Class<?>findMixInClassFor(Class<?> cls)static List<Module>findModules()Method for locating available methods, using JDKServiceLoaderfacility, along with module-provided SPI.static List<Module>findModules(ClassLoader classLoader)Method for locating available methods, using JDKServiceLoaderfacility, along with module-provided SPI.JsonSchemagenerateJsonSchema(Class<?> t)Deprecated.Since 2.6 use external JSON Schema generator (https://github.com/FasterXML/jackson-module-jsonSchema) (which under the hood callsacceptJsonFormatVisitor(JavaType, JsonFormatVisitorWrapper))DateFormatgetDateFormat()DeserializationConfiggetDeserializationConfig()Method that returns the shared defaultDeserializationConfigobject that defines configuration settings for deserialization.DeserializationContextgetDeserializationContext()Method for getting currentDeserializationContext.com.fasterxml.jackson.core.JsonFactorygetFactory()InjectableValuesgetInjectableValues()com.fasterxml.jackson.core.JsonFactorygetJsonFactory()Deprecated.Since 2.1: UsegetFactory()insteadJsonNodeFactorygetNodeFactory()Method that can be used to get hold ofJsonNodeFactorythat this mapper will use when directly constructing rootJsonNodeinstances for Trees.PolymorphicTypeValidatorgetPolymorphicTypeValidator()Accessor for configuredPolymorphicTypeValidatorused for validating polymorphic subtypes used with explicit polymorphic types (annotation-based), but NOT one with "default typing" (seeactivateDefaultTyping(PolymorphicTypeValidator)for details).PropertyNamingStrategygetPropertyNamingStrategy()Set<Object>getRegisteredModuleIds()The set ofModuletypeIds that are registered in this ObjectMapper.SerializationConfiggetSerializationConfig()Method that returns the shared defaultSerializationConfigobject that defines configuration settings for serialization.SerializerFactorygetSerializerFactory()Method for getting currentSerializerFactory.SerializerProvidergetSerializerProvider()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).SerializerProvidergetSerializerProviderInstance()Accessor for constructing and returning aSerializerProviderinstance that may be used for accessing serializers.SubtypeResolvergetSubtypeResolver()Method for accessing subtype resolver in use.TypeFactorygetTypeFactory()Accessor for getting currently configuredTypeFactoryinstance.VisibilityChecker<?>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.booleanisEnabled(com.fasterxml.jackson.core.JsonFactory.Feature f)Convenience method, equivalent to:booleanisEnabled(com.fasterxml.jackson.core.JsonGenerator.Feature f)booleanisEnabled(com.fasterxml.jackson.core.JsonParser.Feature f)booleanisEnabled(com.fasterxml.jackson.core.StreamReadFeature f)booleanisEnabled(com.fasterxml.jackson.core.StreamWriteFeature f)booleanisEnabled(DeserializationFeature f)Method for checking whether given deserialization-specific feature is enabled.booleanisEnabled(MapperFeature f)Method for checking whether givenMapperFeatureis enabled.booleanisEnabled(SerializationFeature f)Method for checking whether given serialization-specific feature is enabled.JsonNodemissingNode()intmixInCount()JsonNodenullNode()ObjectReaderreader()Factory method for constructingObjectReaderwith default settings.ObjectReaderreader(com.fasterxml.jackson.core.Base64Variant defaultBase64)Factory method for constructingObjectReaderthat will use specified Base64 encoding variant for Base64-encoded binary data.ObjectReaderreader(com.fasterxml.jackson.core.FormatSchema schema)Factory method for constructingObjectReaderthat will pass specific schema object toJsonParserused for reading content.ObjectReaderreader(com.fasterxml.jackson.core.type.TypeReference<?> type)Deprecated.Since 2.5, usereaderFor(TypeReference)insteadObjectReaderreader(ContextAttributes attrs)Factory method for constructingObjectReaderthat will use specified default attributes.ObjectReaderreader(DeserializationFeature feature)Factory method for constructingObjectReaderwith specified feature enabled (compared to settings that this mapper instance has).ObjectReaderreader(DeserializationFeature first, DeserializationFeature... other)Factory method for constructingObjectReaderwith specified features enabled (compared to settings that this mapper instance has).ObjectReaderreader(InjectableValues injectableValues)Factory method for constructingObjectReaderthat will use specified injectable values.ObjectReaderreader(JavaType type)Deprecated.Since 2.5, usereaderFor(JavaType)insteadObjectReaderreader(JsonNodeFactory f)Factory method for constructingObjectReaderthat will use specifiedJsonNodeFactoryfor constructing JSON trees.ObjectReaderreader(Class<?> type)Deprecated.Since 2.5, usereaderFor(Class)insteadObjectReaderreaderFor(com.fasterxml.jackson.core.type.TypeReference<?> type)Factory method for constructingObjectReaderthat will read or update instances of specified typeObjectReaderreaderFor(JavaType type)Factory method for constructingObjectReaderthat will read or update instances of specified typeObjectReaderreaderFor(Class<?> type)Factory method for constructingObjectReaderthat will read or update instances of specified typeObjectReaderreaderForUpdating(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.ObjectReaderreaderWithView(Class<?> view)Factory method for constructingObjectReaderthat will deserialize objects using specified JSON View (filter).JsonNodereadTree(byte[] content)Same asreadTree(InputStream)except content read from passed-in byte array.JsonNodereadTree(byte[] content, int offset, int len)Same asreadTree(InputStream)except content read from passed-in byte array.<T extends com.fasterxml.jackson.core.TreeNode>
TreadTree(com.fasterxml.jackson.core.JsonParser p)Method to deserialize JSON content as a treeJsonNode.JsonNodereadTree(File file)Same asreadTree(InputStream)except content read from passed-inFile.JsonNodereadTree(InputStream in)Method to deserialize JSON content as tree expressed using set ofJsonNodeinstances.JsonNodereadTree(Reader r)Same asreadTree(InputStream)except content accessed through passed-inReaderJsonNodereadTree(String content)Same asreadTree(InputStream)except content read from passed-inStringJsonNodereadTree(URL source)Same asreadTree(InputStream)except content read from passed-inURL.<T> TreadValue(byte[] src, int offset, int len, com.fasterxml.jackson.core.type.TypeReference<T> valueTypeRef)<T> TreadValue(byte[] src, int offset, int len, JavaType valueType)<T> TreadValue(byte[] src, int offset, int len, Class<T> valueType)<T> TreadValue(byte[] src, com.fasterxml.jackson.core.type.TypeReference<T> valueTypeRef)<T> TreadValue(byte[] src, JavaType valueType)<T> TreadValue(byte[] src, Class<T> valueType)<T> TreadValue(com.fasterxml.jackson.core.JsonParser p, com.fasterxml.jackson.core.type.ResolvedType valueType)Method to deserialize JSON content into a Java type, reference to which is passed as argument.<T> TreadValue(com.fasterxml.jackson.core.JsonParser p, com.fasterxml.jackson.core.type.TypeReference<T> valueTypeRef)Method to deserialize JSON content into a Java type, reference to which is passed as argument.<T> TreadValue(com.fasterxml.jackson.core.JsonParser p, JavaType valueType)Type-safe overloaded method, basically alias forreadValue(JsonParser, Class).<T> TreadValue(com.fasterxml.jackson.core.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> TreadValue(DataInput src, JavaType valueType)<T> TreadValue(DataInput src, Class<T> valueType)<T> TreadValue(File src, com.fasterxml.jackson.core.type.TypeReference<T> valueTypeRef)Method to deserialize JSON content from given file into given Java type.<T> TreadValue(File src, JavaType valueType)Method to deserialize JSON content from given file into given Java type.<T> TreadValue(File src, Class<T> valueType)Method to deserialize JSON content from given file into given Java type.<T> TreadValue(InputStream src, com.fasterxml.jackson.core.type.TypeReference<T> valueTypeRef)<T> TreadValue(InputStream src, JavaType valueType)<T> TreadValue(InputStream src, Class<T> valueType)<T> TreadValue(Reader src, com.fasterxml.jackson.core.type.TypeReference<T> valueTypeRef)<T> TreadValue(Reader src, JavaType valueType)<T> TreadValue(Reader src, Class<T> valueType)<T> TreadValue(String content, com.fasterxml.jackson.core.type.TypeReference<T> valueTypeRef)Method to deserialize JSON content from given JSON content String.<T> TreadValue(String content, JavaType valueType)Method to deserialize JSON content from given JSON content String.<T> TreadValue(String content, Class<T> valueType)Method to deserialize JSON content from given JSON content String.<T> TreadValue(URL src, com.fasterxml.jackson.core.type.TypeReference<T> valueTypeRef)Same asreadValue(java.net.URL, Class)except that target specified byTypeReference.<T> TreadValue(URL src, JavaType valueType)Same asreadValue(java.net.URL, Class)except that target specified byJavaType.<T> TreadValue(URL src, Class<T> valueType)Method to deserialize JSON content from given resource into given Java type.<T> MappingIterator<T>readValues(com.fasterxml.jackson.core.JsonParser p, com.fasterxml.jackson.core.type.ResolvedType valueType)Convenience method, equivalent in function to:<T> MappingIterator<T>readValues(com.fasterxml.jackson.core.JsonParser p, com.fasterxml.jackson.core.type.TypeReference<T> valueTypeRef)Method for reading sequence of Objects from parser stream.<T> MappingIterator<T>readValues(com.fasterxml.jackson.core.JsonParser p, JavaType valueType)Convenience method, equivalent in function to:<T> MappingIterator<T>readValues(com.fasterxml.jackson.core.JsonParser p, Class<T> valueType)Convenience method, equivalent in function to:ObjectMapperregisterModule(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.ObjectMapperregisterModules(Module... modules)Convenience method for registering specified modules in order; functionally equivalent to:ObjectMapperregisterModules(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)ObjectMappersetAnnotationIntrospector(AnnotationIntrospector ai)Method for settingAnnotationIntrospectorused by this mapper instance for both serialization and deserialization.ObjectMappersetAnnotationIntrospectors(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 aspectsObjectMappersetBase64Variant(com.fasterxml.jackson.core.Base64Variant v)Method that will configure defaultBase64Variantthatbyte[]serializers and deserializers will use.ObjectMappersetConfig(DeserializationConfig config)Method that allows overriding of the underlyingDeserializationConfigobject.ObjectMappersetConfig(SerializationConfig config)Method that allows overriding of the underlyingSerializationConfigobject, which contains serialization-specific configuration settings.ObjectMappersetDateFormat(DateFormat dateFormat)Method for configuring the defaultDateFormatto use when serializing time values as Strings, and deserializing from JSON Strings.ObjectMappersetDefaultLeniency(Boolean b)ObjectMappersetDefaultMergeable(Boolean b)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).ObjectMappersetDefaultPrettyPrinter(com.fasterxml.jackson.core.PrettyPrinter pp)Method for specifyingPrettyPrinterto use when "default pretty-printing" is enabled (by enablingSerializationFeature.INDENT_OUTPUT)ObjectMappersetDefaultPropertyInclusion(com.fasterxml.jackson.annotation.JsonInclude.Include incl)Short-cut for:ObjectMappersetDefaultPropertyInclusion(com.fasterxml.jackson.annotation.JsonInclude.Value incl)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).ObjectMappersetDefaultSetterInfo(com.fasterxml.jackson.annotation.JsonSetter.Value v)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).ObjectMappersetDefaultTyping(TypeResolverBuilder<?> typer)Method for enabling automatic inclusion of type information, using specified handler object for determining which types this affects, as well as details of how information is embedded.ObjectMappersetDefaultVisibility(com.fasterxml.jackson.annotation.JsonAutoDetect.Value vis)Method for setting auto-detection visibility definition defaults, which are in effect unless overridden by annotations (likeJsonAutoDetect) or per-type visibility overrides.ObjectMappersetFilterProvider(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)ObjectsetHandlerInstantiator(HandlerInstantiator hi)Method for configuringHandlerInstantiatorto use for creating instances of handlers (such as serializers, deserializers, type and type id resolvers), given a class.ObjectMappersetInjectableValues(InjectableValues injectableValues)Method for configuringInjectableValueswhich used to find values to inject.ObjectMappersetLocale(Locale l)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<?>>).ObjectMappersetMixInResolver(ClassIntrospector.MixInResolver resolver)Method that can be called to specify given resolver for locating mix-in classes to use, overriding directly added mappings.ObjectMappersetMixIns(Map<Class<?>,Class<?>> sourceMixins)Method to use for defining mix-in annotations to use for augmenting annotations that processable (serializable / deserializable) classes have.ObjectMappersetNodeFactory(JsonNodeFactory f)Method for specifyingJsonNodeFactoryto use for constructing root level tree nodes (via methodcreateObjectNode()ObjectMappersetPolymorphicTypeValidator(PolymorphicTypeValidator ptv)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).ObjectMappersetPropertyInclusion(com.fasterxml.jackson.annotation.JsonInclude.Value incl)Deprecated.ObjectMappersetPropertyNamingStrategy(PropertyNamingStrategy s)Method for setting custom property naming strategy to use.ObjectMappersetSerializationInclusion(com.fasterxml.jackson.annotation.JsonInclude.Include incl)Convenience method, equivalent to calling:ObjectMappersetSerializerFactory(SerializerFactory f)Method for setting specificSerializerFactoryto use for constructing (bean) serializers.ObjectMappersetSerializerProvider(DefaultSerializerProvider p)Method for setting "blueprint"SerializerProviderinstance to use as the base for actual provider instances to use for handling caching ofJsonSerializerinstances.ObjectMappersetSubtypeResolver(SubtypeResolver str)Method for setting custom subtype resolver to use.ObjectMappersetTimeZone(TimeZone tz)Method for overriding default TimeZone to use for formatting.ObjectMappersetTypeFactory(TypeFactory f)Method that can be used to overrideTypeFactoryinstance used by this mapper.ObjectMappersetVisibility(com.fasterxml.jackson.annotation.PropertyAccessor forMethod, com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility visibility)Convenience method that allows changing configuration for underlyingVisibilityCheckers, to change details of what kinds of properties are auto-detected.ObjectMappersetVisibility(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.voidsetVisibilityChecker(VisibilityChecker<?> vc)Deprecated.Since 2.6 usesetVisibility(VisibilityChecker)instead.com.fasterxml.jackson.core.JsonFactorytokenStreamFactory()Method that can be used to get hold ofJsonFactorythat this mapper uses if it needs to constructJsonParsers and/orJsonGenerators.com.fasterxml.jackson.core.JsonParsertreeAsTokens(com.fasterxml.jackson.core.TreeNode n)Method for constructing aJsonParserout of JSON tree representation.<T> TtreeToValue(com.fasterxml.jackson.core.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)Reverse oftreeToValue(com.fasterxml.jackson.core.TreeNode, java.lang.Class<T>); given a value (usually bean), will construct equivalent JSON Tree representation.com.fasterxml.jackson.core.Versionversion()Method that will return version information stored in and read from jar that contains this class.ObjectWriterwriter()Convenience method for constructingObjectWriterwith default settings.ObjectWriterwriter(com.fasterxml.jackson.core.Base64Variant defaultBase64)Factory method for constructingObjectWriterthat will use specified Base64 encoding variant for Base64-encoded binary data.ObjectWriterwriter(com.fasterxml.jackson.core.FormatSchema schema)Factory method for constructingObjectWriterthat will pass specific schema object toJsonGeneratorused for writing content.ObjectWriterwriter(com.fasterxml.jackson.core.io.CharacterEscapes escapes)Factory method for constructingObjectReaderthat will use specified character escaping details for output.ObjectWriterwriter(com.fasterxml.jackson.core.PrettyPrinter pp)Factory method for constructingObjectWriterthat will serialize objects using specified pretty printer for indentation (or if null, no pretty printer)ObjectWriterwriter(ContextAttributes attrs)Factory method for constructingObjectWriterthat will use specified default attributes.ObjectWriterwriter(FilterProvider filterProvider)Factory method for constructingObjectWriterthat will serialize objects using specified filter provider.ObjectWriterwriter(SerializationFeature feature)Factory method for constructingObjectWriterwith specified feature enabled (compared to settings that this mapper instance has).ObjectWriterwriter(SerializationFeature first, SerializationFeature... other)Factory method for constructingObjectWriterwith specified features enabled (compared to settings that this mapper instance has).ObjectWriterwriter(DateFormat df)Factory method for constructingObjectWriterthat will serialize objects using specifiedDateFormat; or, if null passed, using timestamp (64-bit number.ObjectWriterwriterFor(com.fasterxml.jackson.core.type.TypeReference<?> rootType)Factory method for constructingObjectWriterthat will serialize objects using specified root type, instead of actual runtime type of value.ObjectWriterwriterFor(JavaType rootType)Factory method for constructingObjectWriterthat will serialize objects using specified root type, instead of actual runtime type of value.ObjectWriterwriterFor(Class<?> rootType)Factory method for constructingObjectWriterthat will serialize objects using specified root type, instead of actual runtime type of value.ObjectWriterwriterWithDefaultPrettyPrinter()Factory method for constructingObjectWriterthat will serialize objects using the default pretty printer for indentationObjectWriterwriterWithType(com.fasterxml.jackson.core.type.TypeReference<?> rootType)Deprecated.Since 2.5, usewriterFor(TypeReference)insteadObjectWriterwriterWithType(JavaType rootType)Deprecated.Since 2.5, usewriterFor(JavaType)insteadObjectWriterwriterWithType(Class<?> rootType)Deprecated.Since 2.5, usewriterFor(Class)insteadObjectWriterwriterWithView(Class<?> serializationView)Factory method for constructingObjectWriterthat will serialize objects using specified JSON View (filter).voidwriteTree(com.fasterxml.jackson.core.JsonGenerator g, com.fasterxml.jackson.core.TreeNode rootNode)voidwriteTree(com.fasterxml.jackson.core.JsonGenerator g, JsonNode rootNode)Method to serialize given JSON Tree, using generator provided.voidwriteValue(com.fasterxml.jackson.core.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.StringwriteValueAsString(Object value)Method that can be used to serialize any Java value as a String.
-
-
-
Field Detail
-
DEFAULT_ANNOTATION_INTROSPECTOR
protected static final AnnotationIntrospector DEFAULT_ANNOTATION_INTROSPECTOR
-
DEFAULT_BASE
protected static final BaseSettings DEFAULT_BASE
Base settings contain defaults used for allObjectMapperinstances.
-
_jsonFactory
protected final com.fasterxml.jackson.core.JsonFactory _jsonFactory
Factory used to createJsonParserandJsonGeneratorinstances as necessary.
-
_typeFactory
protected TypeFactory _typeFactory
Specific factory used for creatingJavaTypeinstances; needed to allow modules to add more custom type handling (mostly to support types of non-Java JVM languages)
-
_injectableValues
protected InjectableValues _injectableValues
Provider for values to inject in deserialized POJOs.
-
_subtypeResolver
protected SubtypeResolver _subtypeResolver
Thing used for registering sub-types, resolving them to super/sub-types as needed.
-
_configOverrides
protected final ConfigOverrides _configOverrides
Currently active per-type configuration overrides, accessed by declared type of property.- Since:
- 2.9
-
_mixIns
protected SimpleMixInResolver _mixIns
Mapping that defines how to apply mix-in annotations: key is the type to received additional annotations, and value is the type that has annotations to "mix in".Annotations associated with the value classes will be used to override annotations of the key class, associated with the same field or method. They can be further masked by sub-classes: you can think of it as injecting annotations between the target class and its sub-classes (or interfaces)
- Since:
- 2.6 (earlier was a simple
Map
-
_serializationConfig
protected SerializationConfig _serializationConfig
Configuration object that defines basic global settings for the serialization process
-
_serializerProvider
protected DefaultSerializerProvider _serializerProvider
Object that manages access to serializers used for serialization, including caching. It is configured with_serializerFactoryto allow for constructing custom serializers.Note: while serializers are only exposed
SerializerProvider, mappers and readers need to access additional API defined byDefaultSerializerProvider
-
_serializerFactory
protected SerializerFactory _serializerFactory
Serializer factory used for constructing serializers.
-
_deserializationConfig
protected DeserializationConfig _deserializationConfig
Configuration object that defines basic global settings for the serialization process
-
_deserializationContext
protected DefaultDeserializationContext _deserializationContext
Blueprint context object; stored here to allow custom sub-classes. Contains references to objects needed for deserialization construction (cache, factory).
-
_registeredModuleTypes
protected Set<Object> _registeredModuleTypes
Set of module types (as perModule.getTypeId()that have been registered; kept track of iffMapperFeature.IGNORE_DUPLICATE_MODULE_REGISTRATIONSis enabled, so that duplicate registration calls can be ignored (to avoid adding same handlers multiple times, mostly).- Since:
- 2.5
-
_rootDeserializers
protected final ConcurrentHashMap<JavaType,JsonDeserializer<Object>> _rootDeserializers
We will use a separate main-level Map for keeping track of root-level deserializers. This is where most successful cache lookups get resolved. Map will contain resolvers for all kinds of types, including container types: this is different from the component cache which will only cache bean deserializers.Given that we don't expect much concurrency for additions (should very quickly converge to zero after startup), let's explicitly define a low concurrency setting.
Since version 1.5, these may are either "raw" deserializers (when no type information is needed for base type), or type-wrapped deserializers (if it is needed)
-
-
Constructor Detail
-
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
public ObjectMapper(com.fasterxml.jackson.core.JsonFactory jf)
Constructs instance that uses specifiedJsonFactoryfor constructing necessaryJsonParsers and/orJsonGenerators.
-
ObjectMapper
protected ObjectMapper(ObjectMapper src)
Copy-constructor, mostly used to supportcopy().- Since:
- 2.1
-
ObjectMapper
public ObjectMapper(com.fasterxml.jackson.core.JsonFactory jf, DefaultSerializerProvider sp, DefaultDeserializationContext dc)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 Detail
-
defaultClassIntrospector
protected ClassIntrospector defaultClassIntrospector()
Overridable helper method used to construct defaultClassIntrospectorto use.- Since:
- 2.5
-
copy
public ObjectMapper 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
-
_checkInvalidCopy
protected void _checkInvalidCopy(Class<?> exp)
- Since:
- 2.1
-
_newReader
protected ObjectReader _newReader(DeserializationConfig config)
Factory method sub-classes must override, to produceObjectReaderinstances of proper sub-type- Since:
- 2.5
-
_newReader
protected ObjectReader _newReader(DeserializationConfig config, JavaType valueType, Object valueToUpdate, com.fasterxml.jackson.core.FormatSchema schema, InjectableValues injectableValues)
Factory method sub-classes must override, to produceObjectReaderinstances of proper sub-type- Since:
- 2.5
-
_newWriter
protected ObjectWriter _newWriter(SerializationConfig config)
Factory method sub-classes must override, to produceObjectWriterinstances of proper sub-type- Since:
- 2.5
-
_newWriter
protected ObjectWriter _newWriter(SerializationConfig config, com.fasterxml.jackson.core.FormatSchema schema)
Factory method sub-classes must override, to produceObjectWriterinstances of proper sub-type- Since:
- 2.5
-
_newWriter
protected ObjectWriter _newWriter(SerializationConfig config, JavaType rootType, com.fasterxml.jackson.core.PrettyPrinter pp)
Factory method sub-classes must override, to produceObjectWriterinstances of proper sub-type- Since:
- 2.5
-
version
public com.fasterxml.jackson.core.Version version()
Method that will return version information stored in and read from jar that contains this class.- Specified by:
versionin interfacecom.fasterxml.jackson.core.Versioned- Specified by:
versionin classcom.fasterxml.jackson.core.ObjectCodec
-
registerModule
public ObjectMapper registerModule(Module module)
Method for registering a module that can extend functionality provided by this mapper; for example, by adding providers for custom serializers and deserializers.- Parameters:
module- Module to register
-
registerModules
public ObjectMapper registerModules(Module... modules)
Convenience method for registering specified modules in order; functionally equivalent to:for (Module module : modules) { registerModule(module); }- Since:
- 2.2
-
registerModules
public ObjectMapper registerModules(Iterable<? extends Module> modules)
Convenience method for registering specified modules in order; functionally equivalent to:for (Module module : modules) { registerModule(module); }- Since:
- 2.2
-
getRegisteredModuleIds
public Set<Object> getRegisteredModuleIds()
The set ofModuletypeIds that are registered in this ObjectMapper. By default the typeId for a module is it's full class name (seeModule.getTypeId()).- Since:
- 2.9.6
-
findModules
public static List<Module> 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
public static List<Module> findModules(ClassLoader classLoader)
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
public ObjectMapper 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
-
getSerializationConfig
public SerializationConfig 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
public DeserializationConfig 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
public DeserializationContext 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
public ObjectMapper setSerializerFactory(SerializerFactory f)
Method for setting specificSerializerFactoryto use for constructing (bean) serializers.
-
getSerializerFactory
public SerializerFactory 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
public ObjectMapper setSerializerProvider(DefaultSerializerProvider p)
Method for setting "blueprint"SerializerProviderinstance to use as the base for actual provider instances to use for handling caching ofJsonSerializerinstances.
-
getSerializerProvider
public SerializerProvider 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
public SerializerProvider getSerializerProviderInstance()
Accessor for constructing and returning aSerializerProviderinstance that may be used for accessing serializers. This is same as callinggetSerializerProvider(), and callingcreateInstanceon it.- Since:
- 2.7
-
setMixIns
public ObjectMapper setMixIns(Map<Class<?>,Class<?>> sourceMixins)
Method to use for defining mix-in annotations to use for augmenting annotations that processable (serializable / deserializable) classes have. 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
public ObjectMapper addMixIn(Class<?> target, Class<?> mixinSource)
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
public ObjectMapper setMixInResolver(ClassIntrospector.MixInResolver resolver)
Method that can be called to specify given resolver for locating mix-in classes to use, overriding directly added mappings. Note that direct mappings are not cleared, but they are only applied if resolver does not provide mix-in matches.- Since:
- 2.6
-
mixInCount
public int mixInCount()
-
setMixInAnnotations
@Deprecated public void setMixInAnnotations(Map<Class<?>,Class<?>> sourceMixins)
Deprecated.Since 2.5: replaced by a fluent form of the method;setMixIns(java.util.Map<java.lang.Class<?>, java.lang.Class<?>>).
-
addMixInAnnotations
@Deprecated public final void addMixInAnnotations(Class<?> target, Class<?> mixinSource)
Deprecated.Since 2.5: replaced by a fluent form of the method;addMixIn(Class, Class).
-
getVisibilityChecker
public VisibilityChecker<?> 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
public ObjectMapper 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. 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
public ObjectMapper setVisibility(com.fasterxml.jackson.annotation.PropertyAccessor forMethod, com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility visibility)
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
public SubtypeResolver getSubtypeResolver()
Method for accessing subtype resolver in use.
-
setSubtypeResolver
public ObjectMapper setSubtypeResolver(SubtypeResolver str)
Method for setting custom subtype resolver to use.
-
setAnnotationIntrospector
public ObjectMapper setAnnotationIntrospector(AnnotationIntrospector ai)
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:
AnnotationIntrospectorPair
-
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:
AnnotationIntrospectorPair
-
setPropertyNamingStrategy
public ObjectMapper setPropertyNamingStrategy(PropertyNamingStrategy s)
Method for setting custom property naming strategy to use.
-
getPropertyNamingStrategy
public PropertyNamingStrategy getPropertyNamingStrategy()
- Since:
- 2.5
-
setDefaultPrettyPrinter
public ObjectMapper setDefaultPrettyPrinter(com.fasterxml.jackson.core.PrettyPrinter pp)
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 public void setVisibilityChecker(VisibilityChecker<?> vc)
Deprecated.Since 2.6 usesetVisibility(VisibilityChecker)instead.
-
setPolymorphicTypeValidator
public ObjectMapper setPolymorphicTypeValidator(PolymorphicTypeValidator ptv)
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
public PolymorphicTypeValidator 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
public ObjectMapper setSerializationInclusion(com.fasterxml.jackson.annotation.JsonInclude.Include incl)
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 public ObjectMapper setPropertyInclusion(com.fasterxml.jackson.annotation.JsonInclude.Value incl)
Deprecated.- Since:
- 2.7
-
setDefaultPropertyInclusion
public ObjectMapper setDefaultPropertyInclusion(com.fasterxml.jackson.annotation.JsonInclude.Value incl)
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
public ObjectMapper setDefaultPropertyInclusion(com.fasterxml.jackson.annotation.JsonInclude.Include incl)
Short-cut for:setDefaultPropertyInclusion(JsonInclude.Value.construct(incl, incl));
- Since:
- 2.9 (basically rename of
setPropertyInclusion)
-
setDefaultSetterInfo
public ObjectMapper setDefaultSetterInfo(com.fasterxml.jackson.annotation.JsonSetter.Value v)
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
public ObjectMapper setDefaultVisibility(com.fasterxml.jackson.annotation.JsonAutoDetect.Value vis)
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
public ObjectMapper setDefaultMergeable(Boolean b)
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
public ObjectMapper setDefaultLeniency(Boolean b)
- Since:
- 2.10
-
registerSubtypes
public void registerSubtypes(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). Type for given class is determined from appropriate annotation; or if missing, default name (unqualified class name)
-
registerSubtypes
public void registerSubtypes(NamedType... types)
Method for registering specified class as a subtype, so that typename-based resolution can link supertypes to subtypes (as an alternative to using annotations). Name may be provided as part of argument, but if not will be based on annotations or use default name (unqualified class name).
-
registerSubtypes
public void registerSubtypes(Collection<Class<?>> subtypes)
- Since:
- 2.9
-
activateDefaultTyping
public ObjectMapper activateDefaultTyping(PolymorphicTypeValidator ptv)
Convenience method that is equivalent to callingenableDefaultTyping(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 callingenableDefaultTyping(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, com.fasterxml.jackson.annotation.JsonTypeInfo.As includeAs)
Method for enabling automatic inclusion of type information, 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 -- 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
public ObjectMapper deactivateDefaultTyping()
Method for disabling automatic inclusion of type information; if so, only explicitly annotated types (ones withJsonTypeInfo) will have additional embedded type information.
-
setDefaultTyping
public ObjectMapper setDefaultTyping(TypeResolverBuilder<?> typer)
Method for enabling automatic inclusion of type information, using specified handler object for determining which types this affects, as well as details of how information is embedded.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 public ObjectMapper enableDefaultTyping()
Deprecated.Since 2.10 useactivateDefaultTyping(PolymorphicTypeValidator)instead
-
enableDefaultTyping
@Deprecated public ObjectMapper enableDefaultTyping(ObjectMapper.DefaultTyping dti)
Deprecated.Since 2.10 useactivateDefaultTyping(PolymorphicTypeValidator,DefaultTyping)instead
-
enableDefaultTyping
@Deprecated public ObjectMapper enableDefaultTyping(ObjectMapper.DefaultTyping applicability, com.fasterxml.jackson.annotation.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 public ObjectMapper disableDefaultTyping()
Deprecated.Since 2.10 usedeactivateDefaultTyping()instead
-
configOverride
public MutableConfigOverride 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. 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
-
getTypeFactory
public TypeFactory getTypeFactory()
Accessor for getting currently configuredTypeFactoryinstance.
-
setTypeFactory
public ObjectMapper setTypeFactory(TypeFactory f)
Method that can be used to overrideTypeFactoryinstance used by this mapper.Note: will also set
TypeFactorythat deserialization and serialization config objects use.
-
constructType
public JavaType constructType(Type t)
Convenience method for constructingJavaTypeout of given type (typicallyjava.lang.Class), but without explicit context.
-
getNodeFactory
public JsonNodeFactory 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
public ObjectMapper setNodeFactory(JsonNodeFactory f)
Method for specifyingJsonNodeFactoryto use for constructing root level tree nodes (via methodcreateObjectNode()
-
addHandler
public ObjectMapper addHandler(DeserializationProblemHandler h)
Method for adding specifiedDeserializationProblemHandlerto be used for handling specific problems during deserialization.
-
clearProblemHandlers
public ObjectMapper clearProblemHandlers()
Method for removing all registeredDeserializationProblemHandlers instances from this mapper.
-
setConfig
public ObjectMapper setConfig(DeserializationConfig config)
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 public void setFilters(FilterProvider filterProvider)
Deprecated.Since 2.6, usesetFilterProvider(com.fasterxml.jackson.databind.ser.FilterProvider)instead (allows chaining)
-
setFilterProvider
public ObjectMapper setFilterProvider(FilterProvider filterProvider)
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
public ObjectMapper setBase64Variant(com.fasterxml.jackson.core.Base64Variant v)
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
public ObjectMapper setConfig(SerializationConfig config)
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
public com.fasterxml.jackson.core.JsonFactory 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
public com.fasterxml.jackson.core.JsonFactory getFactory()
- Overrides:
getFactoryin classcom.fasterxml.jackson.core.ObjectCodec
-
getJsonFactory
@Deprecated public com.fasterxml.jackson.core.JsonFactory getJsonFactory()
Deprecated.Since 2.1: UsegetFactory()instead- Overrides:
getJsonFactoryin classcom.fasterxml.jackson.core.ObjectCodec
-
setDateFormat
public ObjectMapper setDateFormat(DateFormat dateFormat)
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
public DateFormat getDateFormat()
- Since:
- 2.5
-
setHandlerInstantiator
public Object setHandlerInstantiator(HandlerInstantiator hi)
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
public ObjectMapper setInjectableValues(InjectableValues injectableValues)
Method for configuringInjectableValueswhich used to find values to inject.
-
getInjectableValues
public InjectableValues getInjectableValues()
- Since:
- 2.6
-
setLocale
public ObjectMapper setLocale(Locale l)
Method for overriding default locale to use for formatting. Default value used isLocale.getDefault().
-
setTimeZone
public ObjectMapper setTimeZone(TimeZone tz)
Method for overriding default TimeZone to use for formatting. Default value used is UTC (NOT default TimeZone of JVM).
-
isEnabled
public boolean isEnabled(MapperFeature f)
Method for checking whether givenMapperFeatureis enabled.
-
configure
public ObjectMapper configure(MapperFeature f, boolean state)
-
enable
public ObjectMapper enable(MapperFeature... f)
-
disable
public ObjectMapper disable(MapperFeature... f)
-
isEnabled
public boolean isEnabled(SerializationFeature f)
Method for checking whether given serialization-specific feature is enabled.
-
configure
public ObjectMapper configure(SerializationFeature f, boolean state)
Method for changing state of an on/off serialization feature for this object mapper.
-
enable
public ObjectMapper enable(SerializationFeature f)
Method for enabling specifiedDeserializationConfigfeature. Modifies and returns this instance; no new object is created.
-
enable
public ObjectMapper enable(SerializationFeature first, SerializationFeature... f)
Method for enabling specifiedDeserializationConfigfeatures. Modifies and returns this instance; no new object is created.
-
disable
public ObjectMapper disable(SerializationFeature f)
Method for enabling specifiedDeserializationConfigfeatures. Modifies and returns this instance; no new object is created.
-
disable
public ObjectMapper disable(SerializationFeature first, SerializationFeature... f)
Method for enabling specifiedDeserializationConfigfeatures. Modifies and returns this instance; no new object is created.
-
isEnabled
public boolean isEnabled(DeserializationFeature f)
Method for checking whether given deserialization-specific feature is enabled.
-
configure
public ObjectMapper configure(DeserializationFeature f, boolean state)
Method for changing state of an on/off deserialization feature for this object mapper.
-
enable
public ObjectMapper enable(DeserializationFeature feature)
Method for enabling specifiedDeserializationConfigfeatures. Modifies and returns this instance; no new object is created.
-
enable
public ObjectMapper enable(DeserializationFeature first, DeserializationFeature... f)
Method for enabling specifiedDeserializationConfigfeatures. Modifies and returns this instance; no new object is created.
-
disable
public ObjectMapper disable(DeserializationFeature feature)
Method for enabling specifiedDeserializationConfigfeatures. Modifies and returns this instance; no new object is created.
-
disable
public ObjectMapper disable(DeserializationFeature first, DeserializationFeature... f)
Method for enabling specifiedDeserializationConfigfeatures. Modifies and returns this instance; no new object is created.
-
isEnabled
public boolean isEnabled(com.fasterxml.jackson.core.JsonParser.Feature f)
-
configure
public ObjectMapper configure(com.fasterxml.jackson.core.JsonParser.Feature f, boolean state)
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.
-
enable
public ObjectMapper enable(com.fasterxml.jackson.core.JsonParser.Feature... features)
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.- Since:
- 2.5
-
disable
public ObjectMapper disable(com.fasterxml.jackson.core.JsonParser.Feature... features)
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.- Since:
- 2.5
-
isEnabled
public boolean isEnabled(com.fasterxml.jackson.core.JsonGenerator.Feature f)
-
configure
public ObjectMapper configure(com.fasterxml.jackson.core.JsonGenerator.Feature f, boolean state)
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.
-
enable
public ObjectMapper enable(com.fasterxml.jackson.core.JsonGenerator.Feature... features)
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.- Since:
- 2.5
-
disable
public ObjectMapper disable(com.fasterxml.jackson.core.JsonGenerator.Feature... features)
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.- Since:
- 2.5
-
isEnabled
public boolean isEnabled(com.fasterxml.jackson.core.JsonFactory.Feature f)
Convenience method, equivalent to:getJsonFactory().isEnabled(f);
-
isEnabled
public boolean isEnabled(com.fasterxml.jackson.core.StreamReadFeature f)
- Since:
- 2.10
-
isEnabled
public boolean isEnabled(com.fasterxml.jackson.core.StreamWriteFeature f)
- Since:
- 2.10
-
readValue
public <T> T readValue(com.fasterxml.jackson.core.JsonParser p, Class<T> valueType) throws IOException, com.fasterxml.jackson.core.JsonParseException, JsonMappingExceptionMethod 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 classcom.fasterxml.jackson.core.ObjectCodec- 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)com.fasterxml.jackson.core.JsonParseException- if underlying input contains invalid content of typeJsonParsersupports (JSON for default case)JsonMappingException- if the input JSON structure does not match structure expected for result type (or has other mismatch issues)
-
readValue
public <T> T readValue(com.fasterxml.jackson.core.JsonParser p, com.fasterxml.jackson.core.type.TypeReference<T> valueTypeRef) throws IOException, com.fasterxml.jackson.core.JsonParseException, JsonMappingExceptionMethod 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 classcom.fasterxml.jackson.core.ObjectCodec- 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)com.fasterxml.jackson.core.JsonParseException- if underlying input contains invalid content of typeJsonParsersupports (JSON for default case)JsonMappingException- if the input JSON structure does not match structure expected for result type (or has other mismatch issues)
-
readValue
public final <T> T readValue(com.fasterxml.jackson.core.JsonParser p, com.fasterxml.jackson.core.type.ResolvedType valueType) throws IOException, com.fasterxml.jackson.core.JsonParseException, JsonMappingExceptionMethod 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 classcom.fasterxml.jackson.core.ObjectCodec- 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)com.fasterxml.jackson.core.JsonParseException- if underlying input contains invalid content of typeJsonParsersupports (JSON for default case)JsonMappingException- if the input JSON structure does not match structure expected for result type (or has other mismatch issues)
-
readValue
public <T> T readValue(com.fasterxml.jackson.core.JsonParser p, JavaType valueType) throws IOException, com.fasterxml.jackson.core.JsonParseException, JsonMappingExceptionType-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)com.fasterxml.jackson.core.JsonParseException- if underlying input contains invalid content of typeJsonParsersupports (JSON for default case)JsonMappingException- if the input JSON structure does not match structure expected for result type (or has other mismatch issues)
-
readTree
public <T extends com.fasterxml.jackson.core.TreeNode> T readTree(com.fasterxml.jackson.core.JsonParser p) throws IOException, com.fasterxml.jackson.core.JsonProcessingExceptionMethod 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 classcom.fasterxml.jackson.core.ObjectCodec- 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)com.fasterxml.jackson.core.JsonParseException- if underlying input contains invalid content of typeJsonParsersupports (JSON for default case)com.fasterxml.jackson.core.JsonProcessingException
-
readValues
public <T> MappingIterator<T> readValues(com.fasterxml.jackson.core.JsonParser p, com.fasterxml.jackson.core.type.ResolvedType valueType) throws IOException, com.fasterxml.jackson.core.JsonProcessingException
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 classcom.fasterxml.jackson.core.ObjectCodec- Throws:
IOExceptioncom.fasterxml.jackson.core.JsonProcessingException
-
readValues
public <T> MappingIterator<T> readValues(com.fasterxml.jackson.core.JsonParser p, JavaType valueType) throws IOException, com.fasterxml.jackson.core.JsonProcessingException
Convenience method, equivalent in function to:readerFor(valueType).readValues(p);
Type-safe overload of
readValues(JsonParser, ResolvedType).- Throws:
IOExceptioncom.fasterxml.jackson.core.JsonProcessingException
-
readValues
public <T> MappingIterator<T> readValues(com.fasterxml.jackson.core.JsonParser p, Class<T> valueType) throws IOException, com.fasterxml.jackson.core.JsonProcessingException
Convenience method, equivalent in function to:readerFor(valueType).readValues(p);
Type-safe overload of
readValues(JsonParser, ResolvedType).- Specified by:
readValuesin classcom.fasterxml.jackson.core.ObjectCodec- Throws:
IOExceptioncom.fasterxml.jackson.core.JsonProcessingException
-
readValues
public <T> MappingIterator<T> readValues(com.fasterxml.jackson.core.JsonParser p, com.fasterxml.jackson.core.type.TypeReference<T> valueTypeRef) throws IOException, com.fasterxml.jackson.core.JsonProcessingException
Method for reading sequence of Objects from parser stream.- Specified by:
readValuesin classcom.fasterxml.jackson.core.ObjectCodec- Throws:
IOExceptioncom.fasterxml.jackson.core.JsonProcessingException
-
readTree
public JsonNode readTree(InputStream in) throws IOException
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),JsonParseExceptionwill 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:
com.fasterxml.jackson.core.JsonParseException- if underlying input contains invalid content of typeJsonParsersupports (JSON for default case)IOException
-
readTree
public JsonNode readTree(Reader r) throws IOException
Same asreadTree(InputStream)except content accessed through passed-inReader- Throws:
IOException
-
readTree
public JsonNode readTree(String content) throws com.fasterxml.jackson.core.JsonProcessingException, JsonMappingException
Same asreadTree(InputStream)except content read from passed-inString- Throws:
com.fasterxml.jackson.core.JsonProcessingExceptionJsonMappingException
-
readTree
public JsonNode readTree(byte[] content) throws IOException
Same asreadTree(InputStream)except content read from passed-in byte array.- Throws:
IOException
-
readTree
public JsonNode readTree(byte[] content, int offset, int len) throws IOException
Same asreadTree(InputStream)except content read from passed-in byte array.- Throws:
IOException
-
readTree
public JsonNode readTree(File file) throws IOException, com.fasterxml.jackson.core.JsonProcessingException
Same asreadTree(InputStream)except content read from passed-inFile.- Throws:
IOExceptioncom.fasterxml.jackson.core.JsonProcessingException
-
readTree
public JsonNode readTree(URL source) throws IOException
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(com.fasterxml.jackson.core.JsonGenerator g, Object value) throws IOException, com.fasterxml.jackson.core.JsonGenerationException, JsonMappingExceptionMethod that can be used to serialize any Java value as JSON output, using providedJsonGenerator.- Specified by:
writeValuein classcom.fasterxml.jackson.core.ObjectCodec- Throws:
IOExceptioncom.fasterxml.jackson.core.JsonGenerationExceptionJsonMappingException
-
writeTree
public void writeTree(com.fasterxml.jackson.core.JsonGenerator g, com.fasterxml.jackson.core.TreeNode rootNode) throws IOException, com.fasterxml.jackson.core.JsonProcessingException- Specified by:
writeTreein classcom.fasterxml.jackson.core.ObjectCodec- Throws:
IOExceptioncom.fasterxml.jackson.core.JsonProcessingException
-
writeTree
public void writeTree(com.fasterxml.jackson.core.JsonGenerator g, JsonNode rootNode) throws IOException, com.fasterxml.jackson.core.JsonProcessingExceptionMethod to serialize given JSON Tree, using generator provided.- Throws:
IOExceptioncom.fasterxml.jackson.core.JsonProcessingException
-
createObjectNode
public ObjectNode 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 classcom.fasterxml.jackson.core.ObjectCodec
-
createArrayNode
public ArrayNode 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 classcom.fasterxml.jackson.core.ObjectCodec
-
missingNode
public JsonNode missingNode()
- Overrides:
missingNodein classcom.fasterxml.jackson.core.TreeCodec
-
nullNode
public JsonNode nullNode()
- Overrides:
nullNodein classcom.fasterxml.jackson.core.TreeCodec
-
treeAsTokens
public com.fasterxml.jackson.core.JsonParser treeAsTokens(com.fasterxml.jackson.core.TreeNode n)
Method for constructing aJsonParserout of JSON tree representation.- Specified by:
treeAsTokensin classcom.fasterxml.jackson.core.ObjectCodec- Parameters:
n- Root node of the tree that resulting parser will read from
-
treeToValue
public <T> T treeToValue(com.fasterxml.jackson.core.TreeNode n, Class<T> valueType) throws com.fasterxml.jackson.core.JsonProcessingExceptionConvenience conversion method that will bind data given JSON tree contains into specific value (usually bean) type.Functionally equivalent to:
objectMapper.convertValue(n, valueClass);
- Specified by:
treeToValuein classcom.fasterxml.jackson.core.ObjectCodec- Throws:
com.fasterxml.jackson.core.JsonProcessingException
-
valueToTree
public <T extends JsonNode> T valueToTree(Object fromValue) throws IllegalArgumentException
Reverse oftreeToValue(com.fasterxml.jackson.core.TreeNode, java.lang.Class<T>); given a value (usually bean), will construct equivalent JSON Tree representation. Functionally similar to serializing value into JSON and parsing JSON as tree, but more efficient.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 JSON representation. So if transformation requires actual materialization of JSON (or other data format that this mapper produces), it will be necessary to do actual serialization.- Type Parameters:
T- Actual node type; usually either basicJsonNodeorObjectNode- Parameters:
fromValue- Bean value to convert- Returns:
- (non-null) Root node of the resulting JSON tree: in case of
nullvalue, node for whichJsonNode.isNull()returnstrue. - Throws:
IllegalArgumentException
-
canSerialize
public boolean canSerialize(Class<?> type)
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
public boolean canSerialize(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.- Since:
- 2.3
-
canDeserialize
public boolean canDeserialize(JavaType type)
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
public boolean canDeserialize(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.- Since:
- 2.3
-
readValue
public <T> T readValue(File src, Class<T> valueType) throws IOException, com.fasterxml.jackson.core.JsonParseException, JsonMappingException
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)com.fasterxml.jackson.core.JsonParseException- if underlying input contains invalid content of typeJsonParsersupports (JSON for default case)JsonMappingException- 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, com.fasterxml.jackson.core.type.TypeReference<T> valueTypeRef) throws IOException, com.fasterxml.jackson.core.JsonParseException, JsonMappingException
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)com.fasterxml.jackson.core.JsonParseException- if underlying input contains invalid content of typeJsonParsersupports (JSON for default case)JsonMappingException- 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, com.fasterxml.jackson.core.JsonParseException, JsonMappingException
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)com.fasterxml.jackson.core.JsonParseException- if underlying input contains invalid content of typeJsonParsersupports (JSON for default case)JsonMappingException- 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, com.fasterxml.jackson.core.JsonParseException, JsonMappingException
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)com.fasterxml.jackson.core.JsonParseException- if underlying input contains invalid content of typeJsonParsersupports (JSON for default case)JsonMappingException- 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, com.fasterxml.jackson.core.type.TypeReference<T> valueTypeRef) throws IOException, com.fasterxml.jackson.core.JsonParseException, JsonMappingException
Same asreadValue(java.net.URL, Class)except that target specified byTypeReference.- Throws:
IOExceptioncom.fasterxml.jackson.core.JsonParseExceptionJsonMappingException
-
readValue
public <T> T readValue(URL src, JavaType valueType) throws IOException, com.fasterxml.jackson.core.JsonParseException, JsonMappingException
Same asreadValue(java.net.URL, Class)except that target specified byJavaType.- Throws:
IOExceptioncom.fasterxml.jackson.core.JsonParseExceptionJsonMappingException
-
readValue
public <T> T readValue(String content, Class<T> valueType) throws com.fasterxml.jackson.core.JsonProcessingException, JsonMappingException
Method to deserialize JSON content from given JSON content String.- Throws:
com.fasterxml.jackson.core.JsonParseException- if underlying input contains invalid content of typeJsonParsersupports (JSON for default case)JsonMappingException- if the input JSON structure does not match structure expected for result type (or has other mismatch issues)com.fasterxml.jackson.core.JsonProcessingException
-
readValue
public <T> T readValue(String content, com.fasterxml.jackson.core.type.TypeReference<T> valueTypeRef) throws com.fasterxml.jackson.core.JsonProcessingException, JsonMappingException
Method to deserialize JSON content from given JSON content String.- Throws:
com.fasterxml.jackson.core.JsonParseException- if underlying input contains invalid content of typeJsonParsersupports (JSON for default case)JsonMappingException- if the input JSON structure does not match structure expected for result type (or has other mismatch issues)com.fasterxml.jackson.core.JsonProcessingException
-
readValue
public <T> T readValue(String content, JavaType valueType) throws com.fasterxml.jackson.core.JsonProcessingException, JsonMappingException
Method to deserialize JSON content from given JSON content String.- Throws:
com.fasterxml.jackson.core.JsonParseException- if underlying input contains invalid content of typeJsonParsersupports (JSON for default case)JsonMappingException- if the input JSON structure does not match structure expected for result type (or has other mismatch issues)com.fasterxml.jackson.core.JsonProcessingException
-
readValue
public <T> T readValue(Reader src, Class<T> valueType) throws IOException, com.fasterxml.jackson.core.JsonParseException, JsonMappingException
- Throws:
IOExceptioncom.fasterxml.jackson.core.JsonParseExceptionJsonMappingException
-
readValue
public <T> T readValue(Reader src, com.fasterxml.jackson.core.type.TypeReference<T> valueTypeRef) throws IOException, com.fasterxml.jackson.core.JsonParseException, JsonMappingException
- Throws:
IOExceptioncom.fasterxml.jackson.core.JsonParseExceptionJsonMappingException
-
readValue
public <T> T readValue(Reader src, JavaType valueType) throws IOException, com.fasterxml.jackson.core.JsonParseException, JsonMappingException
- Throws:
IOExceptioncom.fasterxml.jackson.core.JsonParseExceptionJsonMappingException
-
readValue
public <T> T readValue(InputStream src, Class<T> valueType) throws IOException, com.fasterxml.jackson.core.JsonParseException, JsonMappingException
- Throws:
IOExceptioncom.fasterxml.jackson.core.JsonParseExceptionJsonMappingException
-
readValue
public <T> T readValue(InputStream src, com.fasterxml.jackson.core.type.TypeReference<T> valueTypeRef) throws IOException, com.fasterxml.jackson.core.JsonParseException, JsonMappingException
- Throws:
IOExceptioncom.fasterxml.jackson.core.JsonParseExceptionJsonMappingException
-
readValue
public <T> T readValue(InputStream src, JavaType valueType) throws IOException, com.fasterxml.jackson.core.JsonParseException, JsonMappingException
- Throws:
IOExceptioncom.fasterxml.jackson.core.JsonParseExceptionJsonMappingException
-
readValue
public <T> T readValue(byte[] src, Class<T> valueType) throws IOException, com.fasterxml.jackson.core.JsonParseException, JsonMappingException- Throws:
IOExceptioncom.fasterxml.jackson.core.JsonParseExceptionJsonMappingException
-
readValue
public <T> T readValue(byte[] src, int offset, int len, Class<T> valueType) throws IOException, com.fasterxml.jackson.core.JsonParseException, JsonMappingException- Throws:
IOExceptioncom.fasterxml.jackson.core.JsonParseExceptionJsonMappingException
-
readValue
public <T> T readValue(byte[] src, com.fasterxml.jackson.core.type.TypeReference<T> valueTypeRef) throws IOException, com.fasterxml.jackson.core.JsonParseException, JsonMappingException- Throws:
IOExceptioncom.fasterxml.jackson.core.JsonParseExceptionJsonMappingException
-
readValue
public <T> T readValue(byte[] src, int offset, int len, com.fasterxml.jackson.core.type.TypeReference<T> valueTypeRef) throws IOException, com.fasterxml.jackson.core.JsonParseException, JsonMappingException- Throws:
IOExceptioncom.fasterxml.jackson.core.JsonParseExceptionJsonMappingException
-
readValue
public <T> T readValue(byte[] src, JavaType valueType) throws IOException, com.fasterxml.jackson.core.JsonParseException, JsonMappingException- Throws:
IOExceptioncom.fasterxml.jackson.core.JsonParseExceptionJsonMappingException
-
readValue
public <T> T readValue(byte[] src, int offset, int len, JavaType valueType) throws IOException, com.fasterxml.jackson.core.JsonParseException, JsonMappingException- Throws:
IOExceptioncom.fasterxml.jackson.core.JsonParseExceptionJsonMappingException
-
readValue
public <T> T readValue(DataInput src, Class<T> valueType) throws IOException
- Throws:
IOException
-
readValue
public <T> T readValue(DataInput src, JavaType valueType) throws IOException
- Throws:
IOException
-
writeValue
public void writeValue(File resultFile, Object value) throws IOException, com.fasterxml.jackson.core.JsonGenerationException, JsonMappingException
Method that can be used to serialize any Java value as JSON output, written to File provided.- Throws:
IOExceptioncom.fasterxml.jackson.core.JsonGenerationExceptionJsonMappingException
-
writeValue
public void writeValue(OutputStream out, Object value) throws IOException, com.fasterxml.jackson.core.JsonGenerationException, JsonMappingException
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).- Throws:
IOExceptioncom.fasterxml.jackson.core.JsonGenerationExceptionJsonMappingException
-
writeValue
public void writeValue(DataOutput out, Object value) throws IOException
- Throws:
IOException- Since:
- 2.8
-
writeValue
public void writeValue(Writer w, Object value) throws IOException, com.fasterxml.jackson.core.JsonGenerationException, JsonMappingException
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).- Throws:
IOExceptioncom.fasterxml.jackson.core.JsonGenerationExceptionJsonMappingException
-
writeValueAsString
public String writeValueAsString(Object value) throws com.fasterxml.jackson.core.JsonProcessingException
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:
com.fasterxml.jackson.core.JsonProcessingException
-
writeValueAsBytes
public byte[] writeValueAsBytes(Object value) throws com.fasterxml.jackson.core.JsonProcessingException
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:
com.fasterxml.jackson.core.JsonProcessingException
-
writer
public ObjectWriter writer()
Convenience method for constructingObjectWriterwith default settings.
-
writer
public ObjectWriter writer(SerializationFeature feature)
Factory method for constructingObjectWriterwith specified feature enabled (compared to settings that this mapper instance has).
-
writer
public ObjectWriter writer(SerializationFeature first, SerializationFeature... other)
Factory method for constructingObjectWriterwith specified features enabled (compared to settings that this mapper instance has).
-
writer
public ObjectWriter writer(DateFormat df)
Factory method for constructingObjectWriterthat will serialize objects using specifiedDateFormat; or, if null passed, using timestamp (64-bit number.
-
writerWithView
public ObjectWriter writerWithView(Class<?> serializationView)
Factory method for constructingObjectWriterthat will serialize objects using specified JSON View (filter).
-
writerFor
public ObjectWriter writerFor(Class<?> rootType)
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
public ObjectWriter writerFor(com.fasterxml.jackson.core.type.TypeReference<?> rootType)
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
public ObjectWriter writerFor(JavaType rootType)
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
public ObjectWriter writer(com.fasterxml.jackson.core.PrettyPrinter pp)
Factory method for constructingObjectWriterthat will serialize objects using specified pretty printer for indentation (or if null, no pretty printer)
-
writerWithDefaultPrettyPrinter
public ObjectWriter writerWithDefaultPrettyPrinter()
Factory method for constructingObjectWriterthat will serialize objects using the default pretty printer for indentation
-
writer
public ObjectWriter writer(FilterProvider filterProvider)
Factory method for constructingObjectWriterthat will serialize objects using specified filter provider.
-
writer
public ObjectWriter writer(com.fasterxml.jackson.core.FormatSchema schema)
Factory method for constructingObjectWriterthat will pass specific schema object toJsonGeneratorused for writing content.- Parameters:
schema- Schema to pass to generator
-
writer
public ObjectWriter writer(com.fasterxml.jackson.core.Base64Variant defaultBase64)
Factory method for constructingObjectWriterthat will use specified Base64 encoding variant for Base64-encoded binary data.- Since:
- 2.1
-
writer
public ObjectWriter writer(com.fasterxml.jackson.core.io.CharacterEscapes escapes)
Factory method for constructingObjectReaderthat will use specified character escaping details for output.- Since:
- 2.3
-
writer
public ObjectWriter writer(ContextAttributes attrs)
Factory method for constructingObjectWriterthat will use specified default attributes.- Since:
- 2.3
-
writerWithType
@Deprecated public ObjectWriter writerWithType(Class<?> rootType)
Deprecated.Since 2.5, usewriterFor(Class)instead
-
writerWithType
@Deprecated public ObjectWriter writerWithType(com.fasterxml.jackson.core.type.TypeReference<?> rootType)
Deprecated.Since 2.5, usewriterFor(TypeReference)instead
-
writerWithType
@Deprecated public ObjectWriter writerWithType(JavaType rootType)
Deprecated.Since 2.5, usewriterFor(JavaType)instead
-
reader
public ObjectReader reader()
Factory method for constructingObjectReaderwith default settings. Note that the resulting instance is NOT usable as is, without defining expected value type.
-
reader
public ObjectReader reader(DeserializationFeature feature)
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
public ObjectReader reader(DeserializationFeature first, DeserializationFeature... other)
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
public ObjectReader 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. 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
public ObjectReader readerFor(JavaType type)
Factory method for constructingObjectReaderthat will read or update instances of specified type- Since:
- 2.6
-
readerFor
public ObjectReader readerFor(Class<?> type)
Factory method for constructingObjectReaderthat will read or update instances of specified type- Since:
- 2.6
-
readerFor
public ObjectReader readerFor(com.fasterxml.jackson.core.type.TypeReference<?> type)
Factory method for constructingObjectReaderthat will read or update instances of specified type- Since:
- 2.6
-
reader
public ObjectReader reader(JsonNodeFactory f)
Factory method for constructingObjectReaderthat will use specifiedJsonNodeFactoryfor constructing JSON trees.
-
reader
public ObjectReader reader(com.fasterxml.jackson.core.FormatSchema schema)
Factory method for constructingObjectReaderthat will pass specific schema object toJsonParserused for reading content.- Parameters:
schema- Schema to pass to parser
-
reader
public ObjectReader reader(InjectableValues injectableValues)
Factory method for constructingObjectReaderthat will use specified injectable values.- Parameters:
injectableValues- Injectable values to use
-
readerWithView
public ObjectReader readerWithView(Class<?> view)
Factory method for constructingObjectReaderthat will deserialize objects using specified JSON View (filter).
-
reader
public ObjectReader reader(com.fasterxml.jackson.core.Base64Variant defaultBase64)
Factory method for constructingObjectReaderthat will use specified Base64 encoding variant for Base64-encoded binary data.- Since:
- 2.1
-
reader
public ObjectReader reader(ContextAttributes attrs)
Factory method for constructingObjectReaderthat will use specified default attributes.- Since:
- 2.3
-
reader
@Deprecated public ObjectReader reader(JavaType type)
Deprecated.Since 2.5, usereaderFor(JavaType)instead
-
reader
@Deprecated public ObjectReader reader(Class<?> type)
Deprecated.Since 2.5, usereaderFor(Class)instead
-
reader
@Deprecated public ObjectReader reader(com.fasterxml.jackson.core.type.TypeReference<?> type)
Deprecated.Since 2.5, usereaderFor(TypeReference)instead
-
convertValue
public <T> T convertValue(Object fromValue, Class<T> toValueType) throws IllegalArgumentException
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, com.fasterxml.jackson.core.type.TypeReference<T> toValueTypeRef) throws IllegalArgumentException
- Throws:
IllegalArgumentException
-
convertValue
public <T> T convertValue(Object fromValue, JavaType toValueType) throws IllegalArgumentException
- Throws:
IllegalArgumentException
-
_convert
protected Object _convert(Object fromValue, JavaType toValueType) throws IllegalArgumentException
Actual conversion implementation: instead of using existing read and write methods, much of code is inlined. Reason for this is that we must avoid root value wrapping/unwrapping both for efficiency and for correctness. If root value wrapping/unwrapping is actually desired, caller must use explicitwriteValueandreadValuemethods.- Throws:
IllegalArgumentException
-
updateValue
public <T> T updateValue(T valueToUpdate, Object overrides) throws JsonMappingExceptionConvenience 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 public JsonSchema generateJsonSchema(Class<?> t) throws JsonMappingException
Deprecated.Since 2.6 use external JSON Schema generator (https://github.com/FasterXML/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
-
_constructDefaultTypeResolverBuilder
protected TypeResolverBuilder<?> _constructDefaultTypeResolverBuilder(ObjectMapper.DefaultTyping applicability, PolymorphicTypeValidator ptv)
Overridable factory method, separate to allow format-specific mappers (and specifically XML-backed one, currently) to offer customTypeResolverBuildersubtypes.- Since:
- 2.10
-
_serializerProvider
protected DefaultSerializerProvider _serializerProvider(SerializationConfig config)
Overridable helper method used for constructingSerializerProviderto use for serialization.
-
_configAndWriteValue
protected final void _configAndWriteValue(com.fasterxml.jackson.core.JsonGenerator g, Object value) throws IOExceptionMethod called to configure the generator as necessary and then call write functionality- Throws:
IOException
-
_readValue
protected Object _readValue(DeserializationConfig cfg, com.fasterxml.jackson.core.JsonParser p, JavaType valueType) throws IOException
Actual implementation of value reading+binding operation.- Throws:
IOException
-
_readMapAndClose
protected Object _readMapAndClose(com.fasterxml.jackson.core.JsonParser p0, JavaType valueType) throws IOException
- Throws:
IOException
-
_readTreeAndClose
protected JsonNode _readTreeAndClose(com.fasterxml.jackson.core.JsonParser p0) throws IOException
Similar to_readMapAndClose(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.databind.JavaType)but specialized forJsonNodereading.- Throws:
IOException- Since:
- 2.9
-
_unwrapAndDeserialize
protected Object _unwrapAndDeserialize(com.fasterxml.jackson.core.JsonParser p, DeserializationContext ctxt, DeserializationConfig config, JavaType rootType, JsonDeserializer<Object> deser) throws IOException
- Throws:
IOException
-
createDeserializationContext
protected DefaultDeserializationContext createDeserializationContext(com.fasterxml.jackson.core.JsonParser p, DeserializationConfig cfg)
Internal helper method called to create an instance ofDeserializationContextfor deserializing a single root value. Can be overridden if a custom context is needed.
-
_initForReading
protected com.fasterxml.jackson.core.JsonToken _initForReading(com.fasterxml.jackson.core.JsonParser p, JavaType targetType) throws IOExceptionMethod called to ensure that given parser is ready for reading content for data binding.- Returns:
- First token to be used for data binding after this call: can never be null as exception will be thrown if parser cannot provide more tokens.
- Throws:
IOException- if the underlying input source has problems during parsingcom.fasterxml.jackson.core.JsonParseException- if parser has problems parsing contentJsonMappingException- if the parser does not have any more content to map (note: Json "null" value is considered content; enf-of-stream not)
-
_initForReading
@Deprecated protected com.fasterxml.jackson.core.JsonToken _initForReading(com.fasterxml.jackson.core.JsonParser p) throws IOException
Deprecated.- Throws:
IOException
-
_verifyNoTrailingTokens
protected final void _verifyNoTrailingTokens(com.fasterxml.jackson.core.JsonParser p, DeserializationContext ctxt, JavaType bindType) throws IOException- Throws:
IOException- Since:
- 2.9
-
_findRootDeserializer
protected JsonDeserializer<Object> _findRootDeserializer(DeserializationContext ctxt, JavaType valueType) throws JsonMappingException
Method called to locate deserializer for the passed root-level value.- Throws:
JsonMappingException
-
_verifySchemaType
protected void _verifySchemaType(com.fasterxml.jackson.core.FormatSchema schema)
- Since:
- 2.2
-
-