com.fasterxml.jackson.databind

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


    public class ObjectMapper
    extends com.fasterxml.jackson.core.ObjectCodec
    implements com.fasterxml.jackson.core.Versioned, Serializable
    This mapper (or, data binder, or codec) provides functionality for converting between Java objects (instances of JDK provided core classes, beans), and matching JSON constructs. It will use instances of JsonParser and JsonGenerator for implementing actual reading/writing of JSON.

    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.

    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).

    See Also:
    Serialized Form
    • Field Detail

      • DEFAULT_ANNOTATION_INTROSPECTOR

        protected static final AnnotationIntrospector DEFAULT_ANNOTATION_INTROSPECTOR
      • STD_VISIBILITY_CHECKER

        protected static final VisibilityChecker<?> STD_VISIBILITY_CHECKER
      • _defaultPrettyPrinter

        protected static final com.fasterxml.jackson.core.PrettyPrinter _defaultPrettyPrinter
      • DEFAULT_BASE

        protected static final BaseSettings DEFAULT_BASE
        Base settings contain defaults used for all ObjectMapper instances.
      • _jsonFactory

        protected final com.fasterxml.jackson.core.JsonFactory _jsonFactory
        Factory used to create JsonParser and JsonGenerator instances as necessary.
      • _typeFactory

        protected TypeFactory _typeFactory
        Specific factory used for creating JavaType instances; 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.
      • _rootNames

        protected final RootNameLookup _rootNames
        Cache for root names used when root-wrapping is enabled.
      • _mixInAnnotations

        protected final HashMap<ClassKey,Class<?>> _mixInAnnotations
        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)

      • _serializationConfig

        protected SerializationConfig _serializationConfig
        Configuration object that defines basic global settings for the serialization process
      • _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).
      • _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 default JsonFactory as necessary, use SerializerProvider as its SerializerProvider, and BeanSerializerFactory as its SerializerFactory. 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 specified JsonFactory for constructing necessary JsonParsers and/or JsonGenerators.
      • ObjectMapper

        protected ObjectMapper(ObjectMapper src)
        Copy-constructor, mostly used to support copy().
        Since:
        2.1
      • ObjectMapper

        public ObjectMapper(com.fasterxml.jackson.core.JsonFactory jf,
                    DefaultSerializerProvider sp,
                    DefaultDeserializationContext dc)
        Constructs instance that uses specified JsonFactory for constructing necessary JsonParsers and/or JsonGenerators, and uses given providers for accessing serializers and deserializers.
        Parameters:
        jf - JsonFactory to use: if null, a new MappingJsonFactory will be constructed
        sp - SerializerProvider to use: if null, a SerializerProvider will be constructed
        dc - Blueprint deserialization context instance to use for creating actual context objects; if null, will construct standard DeserializationContext
    • Method Detail

      • defaultClassIntrospector

        protected ClassIntrospector defaultClassIntrospector()
        Overridable helper method used to construct default ClassIntrospector to use.
        Since:
        2.5
      • 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
      • _checkInvalidCopy

        protected void _checkInvalidCopy(Class<?> exp)
        Since:
        2.1
      • _newWriter

        protected ObjectWriter _newWriter(SerializationConfig config,
                              com.fasterxml.jackson.core.FormatSchema schema)
        Factory method sub-classes must override, to produce ObjectWriter instances 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:
        version in interface com.fasterxml.jackson.core.Versioned
        Overrides:
        version in class com.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<Module> modules)
        Convenience method for registering specified modules in order; functionally equivalent to:
           for (Module module : modules) {
              registerModule(module);
           }
        
        Since:
        2.2
      • findModules

        public static 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 List<Module> findModules(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
      • 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.

      • 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.
        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 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
      • findMixInClassFor

        public Class<?> findMixInClassFor(Class<?> cls)
      • mixInCount

        public int mixInCount()
      • 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.
      • setVisibilityChecker

        public void setVisibilityChecker(VisibilityChecker<?> vc)
        Method for setting currently configured visibility checker; object used for determining whether given property element (method, field, constructor) can be auto-detected or not. This default checker is used if no per-class overrides are defined.
      • setVisibility

        public ObjectMapper setVisibility(com.fasterxml.jackson.annotation.PropertyAccessor forMethod,
                                 com.fasterxml.jackson.annotation.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.
      • setSerializationInclusion

        public ObjectMapper setSerializationInclusion(com.fasterxml.jackson.annotation.JsonInclude.Include incl)
        Method for setting defalt POJO property inclusion strategy for serialization.
      • enableDefaultTyping

        public ObjectMapper enableDefaultTyping()
        Convenience method that is equivalent to calling
          enableObjectTyping(DefaultTyping.OBJECT_AND_NON_CONCRETE);
        
      • enableDefaultTyping

        public ObjectMapper enableDefaultTyping(ObjectMapper.DefaultTyping dti)
        Convenience method that is equivalent to calling
          enableObjectTyping(dti, JsonTypeInfo.As.WRAPPER_ARRAY);
        
      • enableDefaultTyping

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

        Parameters:
        applicability - Defines kinds of types for which additional type information is added; see ObjectMapper.DefaultTyping for more information.
      • enableDefaultTypingAsProperty

        public ObjectMapper enableDefaultTypingAsProperty(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 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)
      • disableDefaultTyping

        public ObjectMapper disableDefaultTyping()
        Method for disabling automatic inclusion of type information; if so, only explicitly annotated types (ones with JsonTypeInfo) 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.
        Parameters:
        typer - Type information inclusion handler
      • 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).
      • 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(Type t)
        Convenience method for constructing JavaType out of given type (typically java.lang.Class), but without explicit context.
      • 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()
        

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

        public void setFilters(FilterProvider filterProvider)
        Convenience method that is equivalent to:
          mapper.setFilters(mapper.getSerializationConfig().withFilters(filterProvider));
        

        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.

      • setBase64Variant

        public ObjectMapper setBase64Variant(com.fasterxml.jackson.core.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
      • getFactory

        public com.fasterxml.jackson.core.JsonFactory getFactory()
        Method that can be used to get hold of JsonFactory that this mapper uses if it needs to construct JsonParsers and/or JsonGenerators.
        Overrides:
        getFactory in class com.fasterxml.jackson.core.ObjectCodec
        Returns:
        JsonFactory that this mapper uses when it needs to construct Json parser and generators
      • getJsonFactory

        @Deprecated
        public com.fasterxml.jackson.core.JsonFactory getJsonFactory()
        Deprecated. Since 2.1: Use getFactory() instead
        Overrides:
        getJsonFactory in class com.fasterxml.jackson.core.ObjectCodec
      • setDateFormat

        public ObjectMapper setDateFormat(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 DateFormat getDateFormat()
        Since:
        2.5
      • setHandlerInstantiator

        public 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
      • setTimeZone

        public ObjectMapper setTimeZone(TimeZone tz)
        Method for overriding default TimeZone to use for formatting. Default value used is UTC (NOT local timezone).
      • configure

        public ObjectMapper configure(MapperFeature f,
                             boolean state)
        Method for changing state of an on/off mapper feature for this mapper instance.
      • 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(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 specified JsonParser.Features for parser instances this object mapper creates.

        Note that this is equivalent to directly calling same method on getFactory().

      • enable

        public ObjectMapper enable(com.fasterxml.jackson.core.JsonParser.Feature... features)
        Method for enabling specified JsonParser.Features for parser instances this object mapper creates.

        Note that this is equivalent to directly calling same method on getFactory().

        Since:
        2.5
      • disable

        public ObjectMapper disable(com.fasterxml.jackson.core.JsonParser.Feature... features)
        Method for disabling specified JsonParser.Features for parser instances this object mapper creates.

        Note that this is equivalent to directly calling same method on getFactory().

        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/off JsonGenerator feature for generator instances this object mapper creates.

        Note that this is equivalent to directly calling same method on getFactory().

      • enable

        public ObjectMapper enable(com.fasterxml.jackson.core.JsonGenerator.Feature... features)
        Method for enabling specified JsonGenerator.Features for parser instances this object mapper creates.

        Note that this is equivalent to directly calling same method on getFactory().

        Since:
        2.5
      • disable

        public ObjectMapper disable(com.fasterxml.jackson.core.JsonGenerator.Feature... features)
        Method for disabling specified JsonGenerator.Features for parser instances this object mapper creates.

        Note that this is equivalent to directly calling same method on getFactory().

        Since:
        2.5
      • isEnabled

        public boolean isEnabled(com.fasterxml.jackson.core.JsonFactory.Feature f)
        Convenience method, equivalent to:
          getJsonFactory().isEnabled(f);
        
      • readValue

        public <T> T readValue(com.fasterxml.jackson.core.JsonParser jp,
                      Class<T> valueType)
                    throws IOException,
                           com.fasterxml.jackson.core.JsonParseException,
                           JsonMappingException
        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 can not be introspected when using this method.

        Specified by:
        readValue in class com.fasterxml.jackson.core.ObjectCodec
        Throws:
        IOException
        com.fasterxml.jackson.core.JsonParseException
        JsonMappingException
      • readValue

        public <T> T readValue(com.fasterxml.jackson.core.JsonParser jp,
                      com.fasterxml.jackson.core.type.TypeReference<?> valueTypeRef)
                    throws IOException,
                           com.fasterxml.jackson.core.JsonParseException,
                           JsonMappingException
        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 com.fasterxml.jackson.core.ObjectCodec
        Throws:
        IOException
        com.fasterxml.jackson.core.JsonParseException
        JsonMappingException
      • readValue

        public final <T> T readValue(com.fasterxml.jackson.core.JsonParser jp,
                      com.fasterxml.jackson.core.type.ResolvedType valueType)
                          throws IOException,
                                 com.fasterxml.jackson.core.JsonParseException,
                                 JsonMappingException
        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 com.fasterxml.jackson.core.ObjectCodec
        Throws:
        IOException
        com.fasterxml.jackson.core.JsonParseException
        JsonMappingException
      • readTree

        public <T extends com.fasterxml.jackson.core.TreeNode> T readTree(com.fasterxml.jackson.core.JsonParser jp)
                                                               throws IOException,
                                                                      com.fasterxml.jackson.core.JsonProcessingException
        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).
        Specified by:
        readTree in class com.fasterxml.jackson.core.ObjectCodec
        Throws:
        IOException
        com.fasterxml.jackson.core.JsonProcessingException
      • readValues

        public <T> MappingIterator<T> readValues(com.fasterxml.jackson.core.JsonParser jp,
                                        com.fasterxml.jackson.core.type.ResolvedType valueType)
                                      throws IOException,
                                             com.fasterxml.jackson.core.JsonProcessingException
        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 but rather to the token following it.

        Note that ObjectReader has more complete set of variants.

        Specified by:
        readValues in class com.fasterxml.jackson.core.ObjectCodec
        Throws:
        IOException
        com.fasterxml.jackson.core.JsonProcessingException
      • readValues

        public <T> MappingIterator<T> readValues(com.fasterxml.jackson.core.JsonParser jp,
                                        Class<T> valueType)
                                      throws IOException,
                                             com.fasterxml.jackson.core.JsonProcessingException
        Type-safe overloaded method, basically alias for readValues(JsonParser, ResolvedType).
        Specified by:
        readValues in class com.fasterxml.jackson.core.ObjectCodec
        Throws:
        IOException
        com.fasterxml.jackson.core.JsonProcessingException
      • readValues

        public <T> MappingIterator<T> readValues(com.fasterxml.jackson.core.JsonParser jp,
                                        com.fasterxml.jackson.core.type.TypeReference<?> valueTypeRef)
                                      throws IOException,
                                             com.fasterxml.jackson.core.JsonProcessingException
        Method for reading sequence of Objects from parser stream.
        Specified by:
        readValues in class com.fasterxml.jackson.core.ObjectCodec
        Throws:
        IOException
        com.fasterxml.jackson.core.JsonProcessingException
      • readTree

        public JsonNode readTree(InputStream in)
                          throws IOException,
                                 com.fasterxml.jackson.core.JsonProcessingException
        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).
        Parameters:
        in - Input stream used to read JSON content for building the JSON tree.
        Throws:
        IOException
        com.fasterxml.jackson.core.JsonProcessingException
      • readTree

        public JsonNode readTree(Reader r)
                          throws IOException,
                                 com.fasterxml.jackson.core.JsonProcessingException
        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).
        Parameters:
        r - Reader used to read JSON content for building the JSON tree.
        Throws:
        IOException
        com.fasterxml.jackson.core.JsonProcessingException
      • readTree

        public JsonNode readTree(String content)
                          throws IOException,
                                 com.fasterxml.jackson.core.JsonProcessingException
        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).
        Parameters:
        content - JSON content to parse to build the JSON tree.
        Throws:
        IOException
        com.fasterxml.jackson.core.JsonProcessingException
      • readTree

        public JsonNode readTree(byte[] content)
                          throws IOException,
                                 com.fasterxml.jackson.core.JsonProcessingException
        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).
        Parameters:
        content - JSON content to parse to build the JSON tree.
        Throws:
        IOException
        com.fasterxml.jackson.core.JsonProcessingException
      • readTree

        public JsonNode readTree(File file)
                          throws IOException,
                                 com.fasterxml.jackson.core.JsonProcessingException
        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).
        Parameters:
        file - File of which contents to parse as JSON for building a tree instance
        Throws:
        IOException
        com.fasterxml.jackson.core.JsonProcessingException
      • readTree

        public JsonNode readTree(URL source)
                          throws IOException,
                                 com.fasterxml.jackson.core.JsonProcessingException
        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).
        Parameters:
        source - URL to use for fetching contents to parse as JSON for building a tree instance
        Throws:
        IOException
        com.fasterxml.jackson.core.JsonProcessingException
      • writeValue

        public void writeValue(com.fasterxml.jackson.core.JsonGenerator jgen,
                      Object value)
                        throws IOException,
                               com.fasterxml.jackson.core.JsonGenerationException,
                               JsonMappingException
        Method that can be used to serialize any Java value as JSON output, using provided JsonGenerator.
        Specified by:
        writeValue in class com.fasterxml.jackson.core.ObjectCodec
        Throws:
        IOException
        com.fasterxml.jackson.core.JsonGenerationException
        JsonMappingException
      • writeTree

        public void writeTree(com.fasterxml.jackson.core.JsonGenerator jgen,
                     com.fasterxml.jackson.core.TreeNode rootNode)
                       throws IOException,
                              com.fasterxml.jackson.core.JsonProcessingException
        Specified by:
        writeTree in class com.fasterxml.jackson.core.ObjectCodec
        Throws:
        IOException
        com.fasterxml.jackson.core.JsonProcessingException
      • writeTree

        public void writeTree(com.fasterxml.jackson.core.JsonGenerator jgen,
                     JsonNode rootNode)
                       throws IOException,
                              com.fasterxml.jackson.core.JsonProcessingException
        Method to serialize given JSON Tree, using generator provided.
        Throws:
        IOException
        com.fasterxml.jackson.core.JsonProcessingException
      • createObjectNode

        public ObjectNode createObjectNode()

        Note: return type is co-variant, as basic ObjectCodec abstraction can not refer to concrete node types (as it's part of core package, whereas impls are part of mapper package)

        Specified by:
        createObjectNode in class com.fasterxml.jackson.core.ObjectCodec
      • createArrayNode

        public ArrayNode createArrayNode()

        Note: return type is co-variant, as basic ObjectCodec abstraction can not refer to concrete node types (as it's part of core package, whereas impls are part of mapper package)

        Specified by:
        createArrayNode in class com.fasterxml.jackson.core.ObjectCodec
      • treeAsTokens

        public com.fasterxml.jackson.core.JsonParser treeAsTokens(com.fasterxml.jackson.core.TreeNode n)
        Method for constructing a JsonParser out of JSON tree representation.
        Specified by:
        treeAsTokens in class com.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.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);
        

        Specified by:
        treeToValue in class com.fasterxml.jackson.core.ObjectCodec
        Throws:
        com.fasterxml.jackson.core.JsonProcessingException
      • valueToTree

        public <T extends JsonNode> T valueToTree(Object fromValue)
                                       throws IllegalArgumentException
        Reverse of treeToValue(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: one known difference from actual serialization is that so-called "raw values" are not supported -- since they are opaque sequence of bytes to include (which may or may not be supported by the backend) they can not be converted using this method. It may be possible to support conversions using full serialization, if raw values must be preserved.

        Type Parameters:
        T - Actual node type; usually either basic JsonNode or ObjectNode
        Parameters:
        fromValue - Bean value to convert
        Returns:
        Root node of the resulting JSON tree
        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, 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(Class<?> type,
                           AtomicReference<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)
      • 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 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:
        IOException
        com.fasterxml.jackson.core.JsonGenerationException
        JsonMappingException
      • 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, 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:
        IOException
        com.fasterxml.jackson.core.JsonGenerationException
        JsonMappingException
      • 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 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:
        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 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:
        com.fasterxml.jackson.core.JsonProcessingException
      • writer

        public <W extends ObjectWriter> W writer()
        Convenience method for constructing ObjectWriter with default settings.
      • writer

        public <W extends ObjectWriter> W writer(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 <W extends ObjectWriter> W writerWithView(Class<?> serializationView)
        Factory method for constructing ObjectWriter that will serialize objects using specified JSON View (filter).
      • writerFor

        public <W extends ObjectWriter> W writerFor(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 <W extends ObjectWriter> W writerFor(com.fasterxml.jackson.core.type.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 <W extends ObjectWriter> W 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 <W extends ObjectWriter> W writer(com.fasterxml.jackson.core.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 <W extends ObjectWriter> W writerWithDefaultPrettyPrinter()
        Factory method for constructing ObjectWriter that will serialize objects using the default pretty printer for indentation
      • writer

        public <W extends ObjectWriter> W writer(FilterProvider filterProvider)
        Factory method for constructing ObjectWriter that will serialize objects using specified filter provider.
      • writer

        public <W extends ObjectWriter> W writer(com.fasterxml.jackson.core.FormatSchema schema)
        Factory method for constructing ObjectWriter that will pass specific schema object to JsonGenerator used for writing content.
        Parameters:
        schema - Schema to pass to generator
      • writer

        public <W extends ObjectWriter> W writer(com.fasterxml.jackson.core.Base64Variant defaultBase64)
        Factory method for constructing ObjectWriter that will use specified Base64 encoding variant for Base64-encoded binary data.
        Since:
        2.1
      • writer

        public <W extends ObjectWriter> W writer(com.fasterxml.jackson.core.io.CharacterEscapes escapes)
        Factory method for constructing ObjectReader that will use specified character escaping details for output.
        Since:
        2.3
      • reader

        public <T extends ObjectReader> T 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 <T extends ObjectReader> T 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.
      • reader

        public <T extends ObjectReader> T reader(DeserializationFeature first,
                                        DeserializationFeature... other)
        Factory method for constructing ObjectReader with 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 <T extends ObjectReader> T readerForUpdating(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
      • reader

        public <T extends ObjectReader> T reader(JavaType type)
        Factory method for constructing ObjectReader that will read or update instances of specified type
      • reader

        public <T extends ObjectReader> T reader(Class<?> type)
        Factory method for constructing ObjectReader that will read or update instances of specified type
      • reader

        public <T extends ObjectReader> T reader(com.fasterxml.jackson.core.type.TypeReference<?> type)
        Factory method for constructing ObjectReader that will read or update instances of specified type
      • reader

        public <T extends ObjectReader> T reader(com.fasterxml.jackson.core.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 <T extends ObjectReader> T reader(InjectableValues injectableValues)
        Factory method for constructing ObjectReader that will use specified injectable values.
        Parameters:
        injectableValues - Injectable values to use
      • readerWithView

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

        public <T extends ObjectReader> T reader(com.fasterxml.jackson.core.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(Object fromValue,
                         Class<T> toValueType)
                       throws IllegalArgumentException
        Convenience method for doing two-step conversion from given value, into instance of given value type. This is functionality equivalent to first serializing given value into JSON, then binding JSON data into value of given type, but may be executed without fully serializing into JSON. Same converters (serializers, deserializers) will be used as for data binding, meaning same object mapper configuration works.
        Throws:
        IllegalArgumentException - If conversion fails due to incompatible type; if so, root cause will contain underlying checked exception data binding functionality threw
      • _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 explicit writeValue and readValue methods.
        Throws:
        IllegalArgumentException
      • 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 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
      • _defaultPrettyPrinter

        protected com.fasterxml.jackson.core.PrettyPrinter _defaultPrettyPrinter()
        Helper method that should return default pretty-printer to use for generators constructed by this mapper, when instructed to use default pretty printer.
      • _configAndWriteValue

        protected final void _configAndWriteValue(com.fasterxml.jackson.core.JsonGenerator jgen,
                                Object value)
                                           throws IOException
        Method called to configure the generator as necessary and then call write functionality
        Throws:
        IOException
      • _configAndWriteValue

        protected final void _configAndWriteValue(com.fasterxml.jackson.core.JsonGenerator jgen,
                                Object value,
                                Class<?> viewClass)
                                           throws IOException
        Throws:
        IOException
      • _initForReading

        protected com.fasterxml.jackson.core.JsonToken _initForReading(com.fasterxml.jackson.core.JsonParser p)
                                                                throws IOException
        Method 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 can not provide more tokens.
        Throws:
        IOException - if the underlying input source has problems during parsing
        com.fasterxml.jackson.core.JsonParseException - if parser has problems parsing content
        JsonMappingException - if the parser does not have any more content to map (note: Json "null" value is considered content; enf-of-stream not)
      • _verifySchemaType

        protected void _verifySchemaType(com.fasterxml.jackson.core.FormatSchema schema)
        Since:
        2.2

Copyright © 2014 FasterXML. All Rights Reserved.