Class ObjectMapper

  • All Implemented Interfaces:
    Versioned, java.io.Serializable
    Direct Known Subclasses:
    JsonMapper

    public class ObjectMapper
    extends ObjectCodec
    implements Versioned, java.io.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. ObjectMapper also acts as a factory for more advanced ObjectReader and ObjectWriter classes. Mapper (and ObjectReaders, ObjectWriters it constructs) will use instances of JsonParser and JsonGenerator for implementing actual reading/writing of JSON. Note that although most read and write methods are exposed through this class, some of the functionality is only exposed via ObjectReader and ObjectWriter: specifically, reading/writing of longer sequences of values is only available through ObjectReader.readValues(InputStream) and ObjectWriter.writeValues(OutputStream).

    Simplest usage is of form:

      final ObjectMapper mapper = new ObjectMapper(); // can use static singleton, inject: just make sure to reuse!
      MyValue value = new MyValue();
      // ... and configure
      File newState = new File("my-stuff.json");
      mapper.writeValue(newState, value); // writes JSON serialization of MyValue instance
      // or, read
      MyValue older = mapper.readValue(new File("my-older-stuff.json"), MyValue.class);
    
      // Or if you prefer JSON Tree representation:
      JsonNode root = mapper.readTree(newState);
      // and find values by, for example, using a JsonPointer expression:
      int age = root.at("/personal/age").getValueAsInt(); 
    

    The main conversion API is defined in ObjectCodec, so that implementation details of this class need not be exposed to streaming parser and generator classes. Usage via ObjectCodec is, however, usually only for cases where dependency to ObjectMapper is either not possible (from Streaming API), or undesireable (when only relying on Streaming API).

    Mapper instances are fully thread-safe provided that ALL configuration of the instance occurs before ANY read or write calls. If configuration of a mapper instance is modified after first usage, changes may or may not take effect, and configuration calls themselves may fail. If you need to use different configuration, you have two main possibilities:

    • Construct and use ObjectReader for reading, ObjectWriter for writing. Both types are fully immutable and you can freely create new instances with different configuration using either factory methods of ObjectMapper, or readers/writers themselves. Construction of new ObjectReaders and ObjectWriters 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 ObjectReader and ObjectWriter, you may need to use multiple ObjectMapper instead (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 method copy() which creates a clone of the mapper with specific configuration, and allows configuration of the copied instance before it gets used. Note that copy() operation is as expensive as constructing a new ObjectMapper instance: 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 custom TypeResolverBuilder implementation to limit possible types to instantiate, (using setDefaultTyping(com.fasterxml.jackson.databind.jsontype.TypeResolverBuilder<?>)).

    See Also:
    Serialized Form
    • Method Detail

      • copy

        public ObjectMapper copy()
        Method for creating a new ObjectMapper instance that has same initial configuration as this instance. Note that this also requires making a copy of the underlying JsonFactory instance.

        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
      • version

        public Version version()
        Method that will return version information stored in and read from jar that contains this class.
        Specified by:
        version in interface Versioned
        Specified by:
        version in class ObjectCodec
        Returns:
        Version of the component
      • 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​(java.lang.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 java.util.Set<java.lang.Object> getRegisteredModuleIds()
        The set of Module typeIds that are registered in this ObjectMapper, if (and only if!) MapperFeature.IGNORE_DUPLICATE_MODULE_REGISTRATIONS is enabled AND module being added returns non-null value for its Module.getTypeId().

        NOTE: when using the default SimpleModule constructor, its id is specified as null and as a consequence such module is NOT included in returned set.

        Since:
        2.9.6
      • findModules

        public static java.util.List<Module> findModules()
        Method for locating available methods, using JDK ServiceLoader facility, 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 java.util.List<Module> findModules​(java.lang.ClassLoader classLoader)
        Method for locating available methods, using JDK ServiceLoader facility, 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
      • createGenerator

        public JsonGenerator createGenerator​(java.io.OutputStream out)
                                      throws java.io.IOException
        Factory method for constructing properly initialized JsonGenerator to write content using specified OutputStream. Generator is not managed (or "owned") by mapper: caller is responsible for properly closing it once content generation is complete.
        Throws:
        java.io.IOException
        Since:
        2.11
      • createGenerator

        public JsonGenerator createGenerator​(java.io.OutputStream out,
                                             JsonEncoding enc)
                                      throws java.io.IOException
        Factory method for constructing properly initialized JsonGenerator to write content using specified OutputStream and encoding. Generator is not managed (or "owned") by mapper: caller is responsible for properly closing it once content generation is complete.
        Throws:
        java.io.IOException
        Since:
        2.11
      • createGenerator

        public JsonGenerator createGenerator​(java.io.Writer w)
                                      throws java.io.IOException
        Factory method for constructing properly initialized JsonGenerator to write content using specified Writer. Generator is not managed (or "owned") by mapper: caller is responsible for properly closing it once content generation is complete.
        Throws:
        java.io.IOException
        Since:
        2.11
      • createGenerator

        public JsonGenerator createGenerator​(java.io.File outputFile,
                                             JsonEncoding enc)
                                      throws java.io.IOException
        Factory method for constructing properly initialized JsonGenerator to write content to specified File, using specified encoding. Generator is not managed (or "owned") by mapper: caller is responsible for properly closing it once content generation is complete.
        Throws:
        java.io.IOException
        Since:
        2.11
      • createGenerator

        public JsonGenerator createGenerator​(java.io.DataOutput out)
                                      throws java.io.IOException
        Factory method for constructing properly initialized JsonGenerator to write content using specified DataOutput. Generator is not managed (or "owned") by mapper: caller is responsible for properly closing it once content generation is complete.
        Throws:
        java.io.IOException
        Since:
        2.11
      • createParser

        public JsonParser createParser​(java.io.File src)
                                throws java.io.IOException
        Factory method for constructing properly initialized JsonParser to read content from specified File. Parser is not managed (or "owned") by ObjectMapper: caller is responsible for properly closing it once content reading is complete.
        Throws:
        java.io.IOException
        Since:
        2.11
      • createParser

        public JsonParser createParser​(java.net.URL src)
                                throws java.io.IOException
        Factory method for constructing properly initialized JsonParser to read content from specified File. Parser is not managed (or "owned") by ObjectMapper: caller is responsible for properly closing it once content reading is complete.
        Throws:
        java.io.IOException
        Since:
        2.11
      • createParser

        public JsonParser createParser​(java.io.InputStream in)
                                throws java.io.IOException
        Factory method for constructing properly initialized JsonParser to read content using specified InputStream. Parser is not managed (or "owned") by ObjectMapper: caller is responsible for properly closing it once content reading is complete.
        Throws:
        java.io.IOException
        Since:
        2.11
      • createParser

        public JsonParser createParser​(java.io.Reader r)
                                throws java.io.IOException
        Factory method for constructing properly initialized JsonParser to read content using specified Reader. Parser is not managed (or "owned") by ObjectMapper: caller is responsible for properly closing it once content reading is complete.
        Throws:
        java.io.IOException
        Since:
        2.11
      • createParser

        public JsonParser createParser​(byte[] content)
                                throws java.io.IOException
        Factory method for constructing properly initialized JsonParser to read content from specified byte array. Parser is not managed (or "owned") by ObjectMapper: caller is responsible for properly closing it once content reading is complete.
        Throws:
        java.io.IOException
        Since:
        2.11
      • createParser

        public JsonParser createParser​(byte[] content,
                                       int offset,
                                       int len)
                                throws java.io.IOException
        Factory method for constructing properly initialized JsonParser to read content from specified byte array. Parser is not managed (or "owned") by ObjectMapper: caller is responsible for properly closing it once content reading is complete.
        Throws:
        java.io.IOException
        Since:
        2.11
      • createParser

        public JsonParser createParser​(java.lang.String content)
                                throws java.io.IOException
        Factory method for constructing properly initialized JsonParser to read content from specified String. Parser is not managed (or "owned") by ObjectMapper: caller is responsible for properly closing it once content reading is complete.
        Throws:
        java.io.IOException
        Since:
        2.11
      • createParser

        public JsonParser createParser​(char[] content)
                                throws java.io.IOException
        Factory method for constructing properly initialized JsonParser to read content from specified character array Parser is not managed (or "owned") by ObjectMapper: caller is responsible for properly closing it once content reading is complete.
        Throws:
        java.io.IOException
        Since:
        2.11
      • createParser

        public JsonParser createParser​(char[] content,
                                       int offset,
                                       int len)
                                throws java.io.IOException
        Factory method for constructing properly initialized JsonParser to read content from specified character array. Parser is not managed (or "owned") by ObjectMapper: caller is responsible for properly closing it once content reading is complete.
        Throws:
        java.io.IOException
        Since:
        2.11
      • createParser

        public JsonParser createParser​(java.io.DataInput content)
                                throws java.io.IOException
        Factory method for constructing properly initialized JsonParser to read content using specified DataInput. Parser is not managed (or "owned") by ObjectMapper: caller is responsible for properly closing it once content reading is complete.
        Throws:
        java.io.IOException
        Since:
        2.11
      • createNonBlockingByteArrayParser

        public JsonParser createNonBlockingByteArrayParser()
                                                    throws java.io.IOException
        Factory method for constructing properly initialized JsonParser to read content using non-blocking (asynchronous) mode. Parser is not managed (or "owned") by ObjectMapper: caller is responsible for properly closing it once content reading is complete.
        Throws:
        java.io.IOException
        Since:
        2.11
      • getSerializationConfig

        public SerializationConfig getSerializationConfig()
        Method that returns the shared default SerializationConfig object 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 default DeserializationConfig object 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 current DeserializationContext.

        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.

      • getSerializerFactory

        public SerializerFactory getSerializerFactory()
        Method for getting current SerializerFactory.

        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.

      • getSerializerProviderInstance

        public SerializerProvider getSerializerProviderInstance()
        Accessor for constructing and returning a SerializerProvider instance that may be used for accessing serializers. This is same as calling getSerializerProvider(), and calling createInstance on it.
        Since:
        2.7
      • setMixIns

        public ObjectMapper setMixIns​(java.util.Map<java.lang.Class<?>,​java.lang.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​(java.lang.Class<?> target,
                                     java.lang.Class<?> mixinSource)
        Method to use for adding mix-in annotations to use for augmenting specified class or interface. All annotations from mixinSource are taken to override annotations that target (or its supertypes) has.
        Parameters:
        target - Class (or interface) whose annotations to effectively override
        mixinSource - 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
      • findMixInClassFor

        public java.lang.Class<?> findMixInClassFor​(java.lang.Class<?> cls)
      • mixInCount

        public int mixInCount()
      • addMixInAnnotations

        @Deprecated
        public final void addMixInAnnotations​(java.lang.Class<?> target,
                                              java.lang.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 default VisibilityChecker, 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​(PropertyAccessor forMethod,
                                          JsonAutoDetect.Visibility visibility)
        Convenience method that allows changing configuration for underlying VisibilityCheckers, to change details of what kinds of properties are auto-detected. 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.
      • setSerializationInclusion

        public ObjectMapper setSerializationInclusion​(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.

      • setDefaultPropertyInclusion

        public ObjectMapper setDefaultPropertyInclusion​(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​(JsonInclude.Include incl)
        Short-cut for:
          setDefaultPropertyInclusion(JsonInclude.Value.construct(incl, incl));
        
        Since:
        2.9 (basically rename of setPropertyInclusion)
      • setDefaultSetterInfo

        public ObjectMapper setDefaultSetterInfo​(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​(JsonAutoDetect.Value vis)
        Method for setting auto-detection visibility definition defaults, which are in effect unless overridden by annotations (like JsonAutoDetect) or per-type visibility overrides.
        Since:
        2.9
      • setDefaultMergeable

        public ObjectMapper setDefaultMergeable​(java.lang.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​(java.lang.Boolean b)
        Since:
        2.10
      • registerSubtypes

        public void registerSubtypes​(java.lang.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​(java.util.Collection<java.lang.Class<?>> subtypes)
        Since:
        2.9
      • activateDefaultTyping

        public ObjectMapper activateDefaultTyping​(PolymorphicTypeValidator ptv)
        Convenience method that is equivalent to calling
          activateDefaultTyping(ptv, DefaultTyping.OBJECT_AND_NON_CONCRETE);
        

        NOTE: choice of PolymorphicTypeValidator to 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 calling
          activateDefaultTyping(ptv, dti, JsonTypeInfo.As.WRAPPER_ARRAY);
        

        NOTE: choice of PolymorphicTypeValidator to 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; see ObjectMapper.DefaultTyping for more information.
        Since:
        2.10
      • activateDefaultTyping

        public ObjectMapper activateDefaultTyping​(PolymorphicTypeValidator ptv,
                                                  ObjectMapper.DefaultTyping applicability,
                                                  JsonTypeInfo.As includeAs)
        Method for enabling automatic inclusion of type information ("Default Typing"), needed for proper deserialization of polymorphic types (unless types have been annotated with JsonTypeInfo).

        NOTE: use of JsonTypeInfo.As#EXTERNAL_PROPERTY NOT SUPPORTED; and attempts of do so will throw an IllegalArgumentException to make this limitation explicit.

        NOTE: choice of PolymorphicTypeValidator to 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; see ObjectMapper.DefaultTyping for more information.
        includeAs -
        Since:
        2.10
      • activateDefaultTypingAsProperty

        public ObjectMapper activateDefaultTypingAsProperty​(PolymorphicTypeValidator ptv,
                                                            ObjectMapper.DefaultTyping applicability,
                                                            java.lang.String propertyName)
        Method for enabling automatic inclusion of type information ("Default Typing") -- needed for proper deserialization of polymorphic types (unless types have been annotated with JsonTypeInfo) -- 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 PolymorphicTypeValidator to 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; see ObjectMapper.DefaultTyping for 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 with JsonTypeInfo) will have additional embedded type information.
        Since:
        2.10
      • setDefaultTyping

        public ObjectMapper setDefaultTyping​(TypeResolverBuilder<?> typer)
        Method for enabling automatic inclusion of type information ("Default Typing"), using specified handler object for determining which types this affects, as well as details of how information is embedded.

        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 TypeResolverBuilder that can limit allowed classes to deserialize. Note in particular that StdTypeResolverBuilder DOES NOT limit applicability but creates type (de)serializers for all types.

        Parameters:
        typer - Type information inclusion handler
      • configOverride

        public MutableConfigOverride configOverride​(java.lang.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 do
           mapper.configOverride(java.util.Date.class)
               .setFormat(JsonFormat.Value.forPattern("yyyy-MM-dd"));
        
        to change the default format to use for properties of type Date (possibly further overridden by per-property annotations)
        Since:
        2.8
      • coercionConfigDefaults

        public MutableCoercionConfig coercionConfigDefaults()
        Accessor for MutableCoercionConfig through which default (fallback) coercion configurations can be changed. Note that such settings are only applied if more specific (by logical and physical type) configuration have not been defined.
        Since:
        2.12
      • coercionConfigFor

        public MutableCoercionConfig coercionConfigFor​(java.lang.Class<?> physicalType)
        Accessor for MutableCoercionConfig through which coercion configuration for specified physical target type can be set.
        Since:
        2.12
      • getTypeFactory

        public TypeFactory getTypeFactory()
        Accessor for getting currently configured TypeFactory instance.
      • setTypeFactory

        public ObjectMapper setTypeFactory​(TypeFactory f)
        Method that can be used to override TypeFactory instance used by this mapper.

        Note: will also set TypeFactory that deserialization and serialization config objects use.

      • constructType

        public JavaType constructType​(java.lang.reflect.Type t)
        Convenience method for constructing JavaType out of given type (typically java.lang.Class), but without explicit context.
      • constructType

        public JavaType constructType​(TypeReference<?> typeRef)
        Convenience method for constructing JavaType out of given type reference.
        Since:
        2.12
      • getNodeFactory

        public JsonNodeFactory getNodeFactory()
        Method that can be used to get hold of JsonNodeFactory that this mapper will use when directly constructing root JsonNode instances for Trees.

        Note: this is just a shortcut for calling

           getDeserializationConfig().getNodeFactory()
        
      • setConstructorDetector

        public ObjectMapper setConstructorDetector​(ConstructorDetector cd)
        Method for specifying ConstructorDetector to use for determining some aspects of creator auto-detection (specifically auto-detection of constructor, and in particular behavior with single-argument constructors).
        Since:
        2.12
      • setConfig

        public ObjectMapper setConfig​(DeserializationConfig config)
        Method that allows overriding of the underlying DeserializationConfig object. 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
      • setFilterProvider

        public ObjectMapper setFilterProvider​(FilterProvider filterProvider)
        Method for configuring this mapper to use specified FilterProvider for 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 not ObjectWriters.

        Since:
        2.6
      • setBase64Variant

        public ObjectMapper setBase64Variant​(Base64Variant v)
        Method that will configure default Base64Variant that byte[] 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 underlying SerializationConfig object, 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
      • setDateFormat

        public ObjectMapper setDateFormat​(java.text.DateFormat dateFormat)
        Method for configuring the default DateFormat to use when serializing time values as Strings, and deserializing from JSON Strings. This is preferably to directly modifying SerializationConfig and DeserializationConfig instances. If you need per-request configuration, use writer(DateFormat) to create properly configured ObjectWriter and use that; this because ObjectWriters are thread-safe whereas ObjectMapper itself is only thread-safe when configuring methods (such as this one) are NOT called.
      • getDateFormat

        public java.text.DateFormat getDateFormat()
        Since:
        2.5
      • setHandlerInstantiator

        public java.lang.Object setHandlerInstantiator​(HandlerInstantiator hi)
        Method for configuring HandlerInstantiator to use for creating instances of handlers (such as serializers, deserializers, type and type id resolvers), given a class.
        Parameters:
        hi - Instantiator to use; if null, use the default implementation
      • getInjectableValues

        public InjectableValues getInjectableValues()
        Since:
        2.6
      • setLocale

        public ObjectMapper setLocale​(java.util.Locale l)
        Method for overriding default locale to use for formatting. Default value used is Locale.getDefault().
      • setTimeZone

        public ObjectMapper setTimeZone​(java.util.TimeZone tz)
        Method for overriding default TimeZone to use for formatting. Default value used is UTC (NOT default TimeZone of JVM).
      • configure

        @Deprecated
        public ObjectMapper configure​(MapperFeature f,
                                      boolean state)
        Deprecated.
        Since 2.13 use JsonMapper.builder().configure(...)
      • enable

        @Deprecated
        public ObjectMapper enable​(MapperFeature... f)
        Deprecated.
        Since 2.13 use JsonMapper.builder().enable(...)
      • disable

        @Deprecated
        public ObjectMapper disable​(MapperFeature... f)
        Deprecated.
        Since 2.13 use JsonMapper.builder().disable(...)
      • 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.
      • 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.
      • isEnabled

        public boolean isEnabled​(JsonFactory.Feature f)
        Convenience method, equivalent to:
          getFactory().isEnabled(f);
        
      • readValue

        public <T> T readValue​(JsonParser p,
                               java.lang.Class<T> valueType)
                        throws java.io.IOException,
                               StreamReadException,
                               DatabindException
        Method to deserialize JSON content into a non-container type (it can be an array type, however): typically a bean, array or a wrapper type (like Boolean).

        Note: this method should NOT be used if the result type is a container (Collection or Map. The reason is that due to type erasure, key and value types cannot be introspected when using this method.

        Specified by:
        readValue in class ObjectCodec
        Type Parameters:
        T - Nominal parameter for target type
        Parameters:
        p - Parser to use for decoding content to bind
        valueType - Java value type to bind content to
        Returns:
        Value deserialized
        Throws:
        java.io.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 where DeserializationFeature.WRAP_EXCEPTIONS does NOT result in wrapping of exception even if enabled)
        StreamReadException - if underlying input contains invalid content of type JsonParser supports (JSON for default case)
        DatabindException - if the input JSON structure does not match structure expected for result type (or has other mismatch issues)
      • readValue

        public <T> T readValue​(JsonParser p,
                               TypeReference<T> valueTypeRef)
                        throws java.io.IOException,
                               StreamReadException,
                               DatabindException
        Method to deserialize JSON content into a Java type, reference to which is passed as argument. Type is passed using so-called "super type token" (see ) and specifically needs to be used if the root type is a parameterized (generic) container type.
        Specified by:
        readValue in class ObjectCodec
        Type Parameters:
        T - Nominal parameter for target type
        Parameters:
        p - Parser to use for decoding content to bind
        valueTypeRef - Java value type to bind content to
        Returns:
        Value deserialized
        Throws:
        java.io.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 where DeserializationFeature.WRAP_EXCEPTIONS does NOT result in wrapping of exception even if enabled)
        StreamReadException - if underlying input contains invalid content of type JsonParser supports (JSON for default case)
        DatabindException - if the input JSON structure does not match structure expected for result type (or has other mismatch issues)
      • readValue

        public final <T> T readValue​(JsonParser p,
                                     ResolvedType valueType)
                              throws java.io.IOException,
                                     StreamReadException,
                                     DatabindException
        Method to deserialize JSON content into a Java type, reference to which is passed as argument. Type is passed using Jackson specific type; instance of which can be constructed using TypeFactory.
        Specified by:
        readValue in class ObjectCodec
        Type Parameters:
        T - Nominal parameter for target type
        Parameters:
        p - Parser to use for decoding content to bind
        valueType - Java value type to bind content to
        Returns:
        Value deserialized
        Throws:
        java.io.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 where DeserializationFeature.WRAP_EXCEPTIONS does NOT result in wrapping of exception even if enabled)
        StreamReadException - if underlying input contains invalid content of type JsonParser supports (JSON for default case)
        DatabindException - if the input JSON structure does not match structure expected for result type (or has other mismatch issues)
      • readTree

        public <T extends TreeNode> T readTree​(JsonParser p)
                                        throws java.io.IOException
        Method to deserialize JSON content as a tree JsonNode. Returns JsonNode that represents the root of the resulting tree, if there was content to read, or null if no more content is accessible via passed JsonParser.

        NOTE! Behavior with end-of-input (no more content) differs between this readTree method, and all other methods that take input source: latter will return "missing node", NOT null

        Specified by:
        readTree in class ObjectCodec
        Returns:
        a JsonNode, if valid JSON content found; null if input has no content to bind -- note, however, that if JSON null token is found, it will be represented as a non-null JsonNode (one that returns true for JsonNode.isNull()
        Throws:
        java.io.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 where DeserializationFeature.WRAP_EXCEPTIONS does NOT result in wrapping of exception even if enabled)
        StreamReadException - if underlying input contains invalid content of type JsonParser supports (JSON for default case)
      • readValues

        public <T> MappingIterator<T> readValues​(JsonParser p,
                                                 ResolvedType valueType)
                                          throws java.io.IOException
        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 JsonParser MUST 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 surrounding START_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 ObjectReader has more complete set of variants.

        Specified by:
        readValues in class ObjectCodec
        Type Parameters:
        T - Nominal parameter for target type
        Parameters:
        p - Parser to use for decoding content to bind
        valueType - Java value type to bind content to
        Returns:
        Iterator for incrementally deserializing values
        Throws:
        java.io.IOException - for low-level read issues, or JsonParseException for decoding problems
      • readValues

        public <T> MappingIterator<T> readValues​(JsonParser p,
                                                 java.lang.Class<T> valueType)
                                          throws java.io.IOException
        Convenience method, equivalent in function to:
           readerFor(valueType).readValues(p);
        

        Type-safe overload of readValues(JsonParser, ResolvedType).

        Specified by:
        readValues in class ObjectCodec
        Type Parameters:
        T - Nominal parameter for target type
        Parameters:
        p - Parser to use for decoding content to bind
        valueType - Java value type to bind content to
        Returns:
        Iterator for incrementally deserializing values
        Throws:
        java.io.IOException - for low-level read issues, or JsonParseException for decoding problems
      • readValues

        public <T> MappingIterator<T> readValues​(JsonParser p,
                                                 TypeReference<T> valueTypeRef)
                                          throws java.io.IOException
        Method for reading sequence of Objects from parser stream.
        Specified by:
        readValues in class ObjectCodec
        Type Parameters:
        T - Nominal parameter for target type
        Parameters:
        p - Parser to use for decoding content to bind
        valueTypeRef - Java value type to bind content to
        Returns:
        Iterator for incrementally deserializing values
        Throws:
        java.io.IOException - for low-level read issues, or JsonParseException for decoding problems
      • readTree

        public JsonNode readTree​(java.io.InputStream in)
                          throws java.io.IOException
        Method to deserialize JSON content as tree expressed using set of JsonNode instances. 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 IOException will be thrown. If a parsing problem occurs (invalid JSON), StreamReadException will be thrown. If no content is found from input (end-of-input), Java null will 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 JSON null token is found, it will be represented as a non-null JsonNode (one that returns true for JsonNode.isNull()
        Throws:
        StreamReadException - if underlying input contains invalid content of type JsonParser supports (JSON for default case)
        java.io.IOException
      • readTree

        public JsonNode readTree​(java.io.Reader r)
                          throws java.io.IOException
        Same as readTree(InputStream) except content accessed through passed-in Reader
        Throws:
        java.io.IOException
      • readTree

        public JsonNode readTree​(byte[] content)
                          throws java.io.IOException
        Same as readTree(InputStream) except content read from passed-in byte array.
        Throws:
        java.io.IOException
      • readTree

        public JsonNode readTree​(byte[] content,
                                 int offset,
                                 int len)
                          throws java.io.IOException
        Same as readTree(InputStream) except content read from passed-in byte array.
        Throws:
        java.io.IOException
      • readTree

        public JsonNode readTree​(java.io.File file)
                          throws java.io.IOException
        Same as readTree(InputStream) except content read from passed-in File.
        Throws:
        java.io.IOException
      • readTree

        public JsonNode readTree​(java.net.URL source)
                          throws java.io.IOException
        Same as readTree(InputStream) except content read from passed-in URL.

        NOTE: handling of URL is delegated to JsonFactory.createParser(java.net.URL) and usually simply calls URL.openStream(), meaning no special handling is done. If different HTTP connection options are needed you will need to create InputStream separately.

        Throws:
        java.io.IOException
      • writeTree

        public void writeTree​(JsonGenerator g,
                              TreeNode rootNode)
                       throws java.io.IOException
        Description copied from class: ObjectCodec
        Method for serializing JSON content from given Tree instance, using specified generator.
        Specified by:
        writeTree in class ObjectCodec
        Parameters:
        g - Generator to use for serializing value
        rootNode - Tree to serialize
        Throws:
        java.io.IOException - for low-level write issues, or JsonGenerationException for decoding problems
      • writeTree

        public void writeTree​(JsonGenerator g,
                              JsonNode rootNode)
                       throws java.io.IOException
        Method to serialize given JSON Tree, using generator provided.
        Throws:
        java.io.IOException
      • 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:
        createObjectNode in class ObjectCodec
        Returns:
        Object node created
      • 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:
        createArrayNode in class ObjectCodec
        Returns:
        Array node created
      • missingNode

        public JsonNode missingNode()
        Overrides:
        missingNode in class TreeCodec
        Returns:
        Node that represents "missing" node during traversal: something referenced but that does not exist in content model
      • nullNode

        public JsonNode nullNode()
        Overrides:
        nullNode in class TreeCodec
        Returns:
        Node that represents explict null value in content
      • treeAsTokens

        public JsonParser treeAsTokens​(TreeNode n)
        Method for constructing a JsonParser out of JSON tree representation.
        Specified by:
        treeAsTokens in class ObjectCodec
        Parameters:
        n - Root node of the tree that resulting parser will read from
        Returns:
        Parser constructed for traversing over contents of specified node
      • treeToValue

        public <T> T treeToValue​(TreeNode n,
                                 java.lang.Class<T> valueType)
                          throws java.lang.IllegalArgumentException,
                                 JsonProcessingException
        Convenience conversion method that will bind data given JSON tree contains into specific value (usually bean) type.

        Functionally equivalent to:

           objectMapper.convertValue(n, valueClass);
        

        Note: inclusion of throws JsonProcessingException is not accidental since while there can be no input decoding problems, it is possible that content does not match target type: in such case various DatabindExceptions are possible. In addition IllegalArgumentException is possible in some cases, depending on whether DeserializationFeature.WRAP_EXCEPTIONS is enabled or not.

        Specified by:
        treeToValue in class ObjectCodec
        Type Parameters:
        T - Nominal parameter for target type
        Parameters:
        n - Tree to convert
        valueType - Java target value type to convert content to
        Returns:
        Converted value instance
        Throws:
        JsonProcessingException - if structural conversion fails
        java.lang.IllegalArgumentException
      • valueToTree

        public <T extends JsonNode> T valueToTree​(java.lang.Object fromValue)
                                           throws java.lang.IllegalArgumentException
        Method that is reverse of treeToValue(com.fasterxml.jackson.core.TreeNode, java.lang.Class<T>): it will convert given Java value (usually bean) into its equivalent Tree mode JsonNode representation. Functionally similar to serializing value into token stream and parsing that stream back as tree model node, but more efficient as TokenBuffer is used to contain the intermediate representation instead of fully serialized contents.

        NOTE: while results are usually identical to that of serialization followed by deserialization, this is not always the case. In some cases serialization into intermediate representation will retain encapsulation of things like raw value (RawValue) or basic node identity (JsonNode). If so, result is a valid tree, but values are not re-constructed through actual format representation. So if transformation requires actual materialization of encoded content, it will be necessary to do actual serialization.

        Type Parameters:
        T - Actual node type; usually either basic JsonNode or ObjectNode
        Parameters:
        fromValue - Java value to convert
        Returns:
        (non-null) Root node of the resulting content tree: in case of null value node for which JsonNode.isNull() returns true.
        Throws:
        java.lang.IllegalArgumentException
      • canSerialize

        public boolean canSerialize​(java.lang.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, call canSerialize(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​(java.lang.Class<?> type,
                                    java.util.concurrent.atomic.AtomicReference<java.lang.Throwable> cause)
        Method similar to canSerialize(Class) but that can return actual Throwable that 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 an Exception being 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,
                                      java.util.concurrent.atomic.AtomicReference<java.lang.Throwable> cause)
        Method similar to canDeserialize(JavaType) but that can return actual Throwable that 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​(java.io.File src,
                               java.lang.Class<T> valueType)
                        throws java.io.IOException,
                               StreamReadException,
                               DatabindException
        Method to deserialize JSON content from given file into given Java type.
        Throws:
        java.io.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 where DeserializationFeature.WRAP_EXCEPTIONS does NOT result in wrapping of exception even if enabled)
        StreamReadException - if underlying input contains invalid content of type JsonParser supports (JSON for default case)
        DatabindException - if the input JSON structure does not match structure expected for result type (or has other mismatch issues)
      • readValue

        public <T> T readValue​(java.io.File src,
                               TypeReference<T> valueTypeRef)
                        throws java.io.IOException,
                               StreamReadException,
                               DatabindException
        Method to deserialize JSON content from given file into given Java type.
        Throws:
        java.io.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 where DeserializationFeature.WRAP_EXCEPTIONS does NOT result in wrapping of exception even if enabled)
        StreamReadException - if underlying input contains invalid content of type JsonParser supports (JSON for default case)
        DatabindException - if the input JSON structure does not match structure expected for result type (or has other mismatch issues)
      • readValue

        public <T> T readValue​(java.io.File src,
                               JavaType valueType)
                        throws java.io.IOException,
                               StreamReadException,
                               DatabindException
        Method to deserialize JSON content from given file into given Java type.
        Throws:
        java.io.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 where DeserializationFeature.WRAP_EXCEPTIONS does NOT result in wrapping of exception even if enabled)
        StreamReadException - if underlying input contains invalid content of type JsonParser supports (JSON for default case)
        DatabindException - if the input JSON structure does not match structure expected for result type (or has other mismatch issues)
      • readValue

        public <T> T readValue​(java.net.URL src,
                               java.lang.Class<T> valueType)
                        throws java.io.IOException,
                               StreamReadException,
                               DatabindException
        Method to deserialize JSON content from given resource into given Java type.

        NOTE: handling of URL is delegated to JsonFactory.createParser(java.net.URL) and usually simply calls URL.openStream(), meaning no special handling is done. If different HTTP connection options are needed you will need to create InputStream separately.

        Throws:
        java.io.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 where DeserializationFeature.WRAP_EXCEPTIONS does NOT result in wrapping of exception even if enabled)
        StreamReadException - if underlying input contains invalid content of type JsonParser supports (JSON for default case)
        DatabindException - if the input JSON structure does not match structure expected for result type (or has other mismatch issues)
      • readValue

        public <T> T readValue​(java.io.DataInput src,
                               java.lang.Class<T> valueType)
                        throws java.io.IOException
        Throws:
        java.io.IOException
      • readValue

        public <T> T readValue​(java.io.DataInput src,
                               JavaType valueType)
                        throws java.io.IOException
        Throws:
        java.io.IOException
      • writeValue

        public void writeValue​(java.io.OutputStream out,
                               java.lang.Object value)
                        throws java.io.IOException,
                               StreamWriteException,
                               DatabindException
        Method that can be used to serialize any Java value as JSON output, using output stream provided (using encoding JsonEncoding.UTF8).

        Note: method does not close the underlying stream explicitly here; however, JsonFactory this mapper uses may choose to close the stream depending on its settings (by default, it will try to close it when JsonGenerator we construct is closed).

        Throws:
        java.io.IOException
        StreamWriteException
        DatabindException
      • writeValue

        public void writeValue​(java.io.DataOutput out,
                               java.lang.Object value)
                        throws java.io.IOException
        Throws:
        java.io.IOException
        Since:
        2.8
      • writeValue

        public void writeValue​(java.io.Writer w,
                               java.lang.Object value)
                        throws java.io.IOException,
                               StreamWriteException,
                               DatabindException
        Method that can be used to serialize any Java value as JSON output, using Writer provided.

        Note: method does not close the underlying stream explicitly here; however, JsonFactory this mapper uses may choose to close the stream depending on its settings (by default, it will try to close it when JsonGenerator we construct is closed).

        Throws:
        java.io.IOException
        StreamWriteException
        DatabindException
      • writeValueAsString

        public java.lang.String writeValueAsString​(java.lang.Object value)
                                            throws JsonProcessingException
        Method that can be used to serialize any Java value as a String. Functionally equivalent to calling writeValue(Writer,Object) with StringWriter and constructing String, but more efficient.

        Note: prior to version 2.1, throws clause included IOException; 2.1 removed it.

        Throws:
        JsonProcessingException
      • writeValueAsBytes

        public byte[] writeValueAsBytes​(java.lang.Object value)
                                 throws JsonProcessingException
        Method that can be used to serialize any Java value as a byte array. Functionally equivalent to calling writeValue(Writer,Object) with ByteArrayOutputStream and getting bytes, but more efficient. Encoding used will be UTF-8.

        Note: prior to version 2.1, throws clause included IOException; 2.1 removed it.

        Throws:
        JsonProcessingException
      • writer

        public ObjectWriter writer​(java.text.DateFormat df)
        Factory method for constructing ObjectWriter that will serialize objects using specified DateFormat; or, if null passed, using timestamp (64-bit number.
      • writerWithView

        public ObjectWriter writerWithView​(java.lang.Class<?> serializationView)
        Factory method for constructing ObjectWriter that will serialize objects using specified JSON View (filter).
      • writerFor

        public ObjectWriter writerFor​(java.lang.Class<?> rootType)
        Factory method for constructing ObjectWriter that 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​(TypeReference<?> rootType)
        Factory method for constructing ObjectWriter that 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 constructing ObjectWriter that 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​(PrettyPrinter pp)
        Factory method for constructing ObjectWriter that will serialize objects using specified pretty printer for indentation (or if null, no pretty printer)
      • writerWithDefaultPrettyPrinter

        public ObjectWriter writerWithDefaultPrettyPrinter()
        Factory method for constructing ObjectWriter that will serialize objects using the default pretty printer for indentation
      • writer

        public ObjectWriter writer​(Base64Variant defaultBase64)
        Factory method for constructing ObjectWriter that will use specified Base64 encoding variant for Base64-encoded binary data.
        Since:
        2.1
      • writerWithType

        @Deprecated
        public ObjectWriter writerWithType​(java.lang.Class<?> rootType)
        Deprecated.
        Since 2.5, use writerFor(Class) instead
      • reader

        public ObjectReader reader()
        Factory method for constructing ObjectReader with 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 constructing ObjectReader with 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.
      • readerForUpdating

        public ObjectReader readerForUpdating​(java.lang.Object valueToUpdate)
        Factory method for constructing ObjectReader that 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 of ObjectReader
      • readerFor

        public ObjectReader readerFor​(JavaType type)
        Factory method for constructing ObjectReader that will read or update instances of specified type
        Since:
        2.6
      • readerFor

        public ObjectReader readerFor​(java.lang.Class<?> type)
        Factory method for constructing ObjectReader that will read or update instances of specified type
        Since:
        2.6
      • readerForArrayOf

        public ObjectReader readerForArrayOf​(java.lang.Class<?> type)
        Factory method for constructing ObjectReader that will read values of a type List<type>. Functionally same as:
            readerFor(type[].class);
        
        Since:
        2.11
      • readerForListOf

        public ObjectReader readerForListOf​(java.lang.Class<?> type)
        Factory method for constructing ObjectReader that will read or update instances of a type List<type>. Functionally same as:
            readerFor(new TypeReference<List<type>>() { });
        
        Since:
        2.11
      • readerForMapOf

        public ObjectReader readerForMapOf​(java.lang.Class<?> type)
        Factory method for constructing ObjectReader that will read or update instances of a type Map<String, type> Functionally same as:
            readerFor(new TypeReference<Map<String, type>>() { });
        
        Since:
        2.11
      • reader

        public ObjectReader reader​(FormatSchema schema)
        Factory method for constructing ObjectReader that will pass specific schema object to JsonParser used for reading content.
        Parameters:
        schema - Schema to pass to parser
      • reader

        public ObjectReader reader​(InjectableValues injectableValues)
        Factory method for constructing ObjectReader that will use specified injectable values.
        Parameters:
        injectableValues - Injectable values to use
      • readerWithView

        public ObjectReader readerWithView​(java.lang.Class<?> view)
        Factory method for constructing ObjectReader that will deserialize objects using specified JSON View (filter).
      • reader

        public ObjectReader reader​(Base64Variant defaultBase64)
        Factory method for constructing ObjectReader that will use specified Base64 encoding variant for Base64-encoded binary data.
        Since:
        2.1
      • convertValue

        public <T> T convertValue​(java.lang.Object fromValue,
                                  java.lang.Class<T> toValueType)
                           throws java.lang.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:
        java.lang.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​(java.lang.Object fromValue,
                                  TypeReference<T> toValueTypeRef)
                           throws java.lang.IllegalArgumentException
        Throws:
        java.lang.IllegalArgumentException
      • convertValue

        public <T> T convertValue​(java.lang.Object fromValue,
                                  JavaType toValueType)
                           throws java.lang.IllegalArgumentException
        Throws:
        java.lang.IllegalArgumentException
      • updateValue

        public <T> T updateValue​(T valueToUpdate,
                                 java.lang.Object overrides)
                          throws JsonMappingException
        Convenience method similar to convertValue(Object, JavaType) but one in which

        Implementation is approximately as follows:

        1. Serialize `updateWithValue` into TokenBuffer
        2. Construct ObjectReader with `valueToUpdate` (using readerForUpdating(Object))
        3. Construct JsonParser (using TokenBuffer.asParser())
        4. Update using ObjectReader.readValue(JsonParser).
        5. 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" (see configOverride(Class) and setDefaultMergeable(Boolean)).

        Parameters:
        valueToUpdate - Object to update
        overrides - 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
      • acceptJsonFormatVisitor

        public void acceptJsonFormatVisitor​(java.lang.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 uses Serializer hierarchy and related properties

        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