com.fasterxml.jackson.databind
Class SerializerProvider

java.lang.Object
  extended by com.fasterxml.jackson.databind.SerializerProvider
Direct Known Subclasses:
DefaultSerializerProvider

public abstract class SerializerProvider
extends Object

Class that defines API used by ObjectMapper and JsonSerializers to obtain serializers capable of serializing instances of specific types; as well as the default implementation of the functionality.

Provider handles caching aspects of serializer handling; all construction details are delegated to SerializerFactory instance.

Object life-cycle is such that an initial instance ("blueprint") is created and referenced by ObjectMapper and ObjectWriter intances; but for actual usage, a configured instance is created by using a create method in sub-class DefaultSerializerProvider. Only this instance can be used for actual serialization calls; blueprint object is only to be used for creating instances.


Field Summary
protected  SerializationConfig _config
          Serialization configuration to use for serialization processing.
protected  DateFormat _dateFormat
          Lazily acquired and instantiated formatter object: initialized first time it is needed, reused afterwards.
protected  JsonSerializer<Object> _keySerializer
          Serializer used to output non-null keys of Maps (which will get output as JSON Objects), if not null; if null, us the standard default key serializer.
protected  ReadOnlyClassToSerializerMap _knownSerializers
          For fast lookups, we will have a local non-shared read-only map that contains serializers previously fetched.
protected  JsonSerializer<Object> _nullKeySerializer
          Serializer used to (try to) output a null key, due to an entry of Map having null key.
protected  JsonSerializer<Object> _nullValueSerializer
          Serializer used to output a null value.
protected  RootNameLookup _rootNames
          Helper object for keeping track of introspected root names
protected  Class<?> _serializationView
          View used for currently active serialization, if any.
protected  SerializerCache _serializerCache
          Cache for doing type-to-value-serializer lookups.
protected  SerializerFactory _serializerFactory
          Factory used for constructing actual serializer instances.
protected  JsonSerializer<Object> _unknownTypeSerializer
          Serializer that gets called for values of types for which no serializers can be constructed.
protected static boolean CACHE_UNKNOWN_MAPPINGS
          Setting for determining whether mappings for "unknown classes" should be cached for faster resolution.
static JsonSerializer<Object> DEFAULT_NULL_KEY_SERIALIZER
           
static JsonSerializer<Object> DEFAULT_UNKNOWN_SERIALIZER
           
protected static JavaType TYPE_OBJECT
           
 
Constructor Summary
  SerializerProvider()
          Constructor for creating master (or "blue-print") provider object, which is only used as the template for constructing per-binding instances.
protected SerializerProvider(SerializerProvider src, SerializationConfig config, SerializerFactory f)
          "Copy-constructor", used by sub-classes.
 
Method Summary
protected  JsonSerializer<Object> _createAndCacheUntypedSerializer(Class<?> type, BeanProperty property)
          Method that will try to construct a value serializer; and if one is successfully created, cache it for reuse.
protected  JsonSerializer<Object> _createAndCacheUntypedSerializer(JavaType type, BeanProperty property)
           
protected  JsonSerializer<Object> _createUntypedSerializer(JavaType type, BeanProperty property)
           
protected  DateFormat _dateFormat()
           
protected  JsonSerializer<Object> _findExplicitUntypedSerializer(Class<?> runtimeType, BeanProperty property)
          Method that will try to find a serializer, either from cache or by constructing one; but will not return an "unknown" serializer if this can not be done but rather returns null.
protected  JsonSerializer<Object> _handleContextual(JsonSerializer<?> ser, BeanProperty property)
           
protected  JsonSerializer<Object> _handleContextualResolvable(JsonSerializer<?> ser, BeanProperty property)
          Helper method called to resolve and contextualize given serializer, if and as necessary.
protected  JsonSerializer<Object> _handleResolvable(JsonSerializer<?> ser)
           
protected  void _reportIncompatibleRootType(Object value, JavaType rootType)
           
 boolean canOverrideAccessModifiers()
          Convenience method for accessing serialization view in use (if any); equivalent to:
 JavaType constructSpecializedType(JavaType baseType, Class<?> subclass)
          Convenience method for constructing subtypes, retaining generic type parameter (if any)
 JavaType constructType(Type type)
          Convenience method for constructing JavaType for given JDK type (usually Class)
 void defaultSerializeDateKey(Date date, JsonGenerator jgen)
          Method that will handle serialization of Dates used as Map keys, based on SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS value (and if using textual representation, configured date format)
 void defaultSerializeDateKey(long timestamp, JsonGenerator jgen)
          Method that will handle serialization of Dates used as Map keys, based on SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS value (and if using textual representation, configured date format)
 void defaultSerializeDateValue(Date date, JsonGenerator jgen)
          Method that will handle serialization of Date(-like) values, using SerializationConfig settings to determine expected serialization behavior.
 void defaultSerializeDateValue(long timestamp, JsonGenerator jgen)
          Method that will handle serialization of Date(-like) values, using SerializationConfig settings to determine expected serialization behavior.
 void defaultSerializeField(String fieldName, Object value, JsonGenerator jgen)
          Convenience method that will serialize given field with specified value.
 void defaultSerializeNull(JsonGenerator jgen)
           
 void defaultSerializeValue(Object value, JsonGenerator jgen)
          Convenience method that will serialize given value (which can be null) using standard serializer locating functionality.
 JsonSerializer<Object> findKeySerializer(JavaType keyType, BeanProperty property)
          Method called to get the serializer to use for serializing non-null Map keys.
 JsonSerializer<Object> findNullKeySerializer(JavaType serializationType, BeanProperty property)
          Method called to find a serializer to use for null values for given declared type.
 JsonSerializer<Object> findNullValueSerializer(BeanProperty property)
          Method called to get the serializer to use for serializing null property values.
abstract  WritableObjectId findObjectId(Object forPojo, ObjectIdGenerator<?> generatorType)
          Method called to find the Object Id for given POJO, if one has been generated.
 JsonSerializer<Object> findTypedValueSerializer(Class<?> valueType, boolean cache, BeanProperty property)
          Method called to locate regular serializer, matching type serializer, and if both found, wrap them in a serializer that calls both in correct sequence.
 JsonSerializer<Object> findTypedValueSerializer(JavaType valueType, boolean cache, BeanProperty property)
          Method called to locate regular serializer, matching type serializer, and if both found, wrap them in a serializer that calls both in correct sequence.
 JsonSerializer<Object> findValueSerializer(Class<?> valueType, BeanProperty property)
          Method called to get hold of a serializer for a value of given type; or if no such serializer can be found, a default handler (which may do a best-effort generic serialization or just simply throw an exception when invoked).
 JsonSerializer<Object> findValueSerializer(JavaType valueType, BeanProperty property)
          Similar to findValueSerializer(Class,BeanProperty), but takes full generics-aware type instead of raw class.
 AnnotationIntrospector getAnnotationIntrospector()
          Convenience method for accessing serialization view in use (if any); equivalent to:
 SerializationConfig getConfig()
          Method for accessing configuration for the serialization processing.
 JsonSerializer<Object> getDefaultNullKeySerializer()
           
 JsonSerializer<Object> getDefaultNullValueSerializer()
           
 FilterProvider getFilterProvider()
          Convenience method for accessing provider to find serialization filters used, equivalent to calling:
 Locale getLocale()
          Method for accessing default Locale to use: convenience method for
 Class<?> getSerializationView()
          Convenience method for accessing serialization view in use (if any); equivalent to:
 TimeZone getTimeZone()
          Method for accessing default TimeZone to use: convenience method for
 TypeFactory getTypeFactory()
           
 JsonSerializer<Object> getUnknownTypeSerializer(Class<?> unknownType)
          Method called to get the serializer to use if provider can not determine an actual type-specific serializer to use; typically when none of SerializerFactory instances are able to construct a serializer.
 boolean isEnabled(MapperFeature feature)
          Convenience method for checking whether specified serialization feature is enabled or not.
 boolean isEnabled(SerializationFeature feature)
          Convenience method for checking whether specified serialization feature is enabled or not.
abstract  ObjectIdGenerator<?> objectIdGeneratorInstance(Annotated annotated, ObjectIdInfo objectIdInfo)
           
abstract  JsonSerializer<Object> serializerInstance(Annotated annotated, Object serDef)
          Method that can be called to construct and configure serializer instance, either given a Class to instantiate (with default constructor), or an uninitialized serializer instance.
 void setDefaultKeySerializer(JsonSerializer<Object> ks)
          Method that can be used to specify serializer that will be used to write JSON property names matching null keys for Java Maps (which will throw an exception if try write such property name)
 void setNullKeySerializer(JsonSerializer<Object> nks)
          Method that can be used to specify serializer to use for serializing all non-null JSON property names, unless more specific key serializer is found (i.e.
 void setNullValueSerializer(JsonSerializer<Object> nvs)
          Method that can be used to specify serializer that will be used to write JSON values matching Java null values instead of default one (which simply writes JSON null)
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

TYPE_OBJECT

protected static final JavaType TYPE_OBJECT

CACHE_UNKNOWN_MAPPINGS

protected static final boolean CACHE_UNKNOWN_MAPPINGS
Setting for determining whether mappings for "unknown classes" should be cached for faster resolution. Usually this isn't needed, but maybe it is in some cases?

See Also:
Constant Field Values

DEFAULT_NULL_KEY_SERIALIZER

public static final JsonSerializer<Object> DEFAULT_NULL_KEY_SERIALIZER

DEFAULT_UNKNOWN_SERIALIZER

public static final JsonSerializer<Object> DEFAULT_UNKNOWN_SERIALIZER

_config

protected final SerializationConfig _config
Serialization configuration to use for serialization processing.


_serializationView

protected final Class<?> _serializationView
View used for currently active serialization, if any.


_serializerFactory

protected final SerializerFactory _serializerFactory
Factory used for constructing actual serializer instances.


_serializerCache

protected final SerializerCache _serializerCache
Cache for doing type-to-value-serializer lookups.


_rootNames

protected final RootNameLookup _rootNames
Helper object for keeping track of introspected root names


_unknownTypeSerializer

protected JsonSerializer<Object> _unknownTypeSerializer
Serializer that gets called for values of types for which no serializers can be constructed.

The default serializer will simply thrown an exception.


_keySerializer

protected JsonSerializer<Object> _keySerializer
Serializer used to output non-null keys of Maps (which will get output as JSON Objects), if not null; if null, us the standard default key serializer.


_nullValueSerializer

protected JsonSerializer<Object> _nullValueSerializer
Serializer used to output a null value. Default implementation writes nulls using JsonGenerator.writeNull().


_nullKeySerializer

protected JsonSerializer<Object> _nullKeySerializer
Serializer used to (try to) output a null key, due to an entry of Map having null key. The default implementation will throw an exception if this happens; alternative implementation (like one that would write an Empty String) can be defined.


_knownSerializers

protected final ReadOnlyClassToSerializerMap _knownSerializers
For fast lookups, we will have a local non-shared read-only map that contains serializers previously fetched.


_dateFormat

protected DateFormat _dateFormat
Lazily acquired and instantiated formatter object: initialized first time it is needed, reused afterwards. Used via instances (not blueprints), so that access need not be thread-safe.

Constructor Detail

SerializerProvider

public SerializerProvider()
Constructor for creating master (or "blue-print") provider object, which is only used as the template for constructing per-binding instances.


SerializerProvider

protected SerializerProvider(SerializerProvider src,
                             SerializationConfig config,
                             SerializerFactory f)
"Copy-constructor", used by sub-classes.

Parameters:
src - Blueprint object used as the baseline for this instance
Method Detail

setDefaultKeySerializer

public void setDefaultKeySerializer(JsonSerializer<Object> ks)
Method that can be used to specify serializer that will be used to write JSON property names matching null keys for Java Maps (which will throw an exception if try write such property name)


setNullValueSerializer

public void setNullValueSerializer(JsonSerializer<Object> nvs)
Method that can be used to specify serializer that will be used to write JSON values matching Java null values instead of default one (which simply writes JSON null)


setNullKeySerializer

public void setNullKeySerializer(JsonSerializer<Object> nks)
Method that can be used to specify serializer to use for serializing all non-null JSON property names, unless more specific key serializer is found (i.e. if not custom key serializer has been registered for Java type).

Note that key serializer registration are different from value serializer registrations.


getConfig

public final SerializationConfig getConfig()
Method for accessing configuration for the serialization processing.


isEnabled

public final boolean isEnabled(MapperFeature feature)
Convenience method for checking whether specified serialization feature is enabled or not. Shortcut for:
  getConfig().isEnabled(feature);


isEnabled

public final boolean isEnabled(SerializationFeature feature)
Convenience method for checking whether specified serialization feature is enabled or not. Shortcut for:
  getConfig().isEnabled(feature);


canOverrideAccessModifiers

public final boolean canOverrideAccessModifiers()
Convenience method for accessing serialization view in use (if any); equivalent to:
   getConfig().canOverrideAccessModifiers();


getAnnotationIntrospector

public final AnnotationIntrospector getAnnotationIntrospector()
Convenience method for accessing serialization view in use (if any); equivalent to:
   getConfig().getAnnotationIntrospector();


getSerializationView

public final Class<?> getSerializationView()
Convenience method for accessing serialization view in use (if any); equivalent to:
   getConfig().getSerializationView();


getFilterProvider

public final FilterProvider getFilterProvider()
Convenience method for accessing provider to find serialization filters used, equivalent to calling:
   getConfig().getFilterProvider();


getLocale

public Locale getLocale()
Method for accessing default Locale to use: convenience method for
   getConfig().getLocale();


getTimeZone

public TimeZone getTimeZone()
Method for accessing default TimeZone to use: convenience method for
   getConfig().getTimeZone();


constructType

public JavaType constructType(Type type)
Convenience method for constructing JavaType for given JDK type (usually Class)


constructSpecializedType

public JavaType constructSpecializedType(JavaType baseType,
                                         Class<?> subclass)
Convenience method for constructing subtypes, retaining generic type parameter (if any)


getTypeFactory

public TypeFactory getTypeFactory()

findObjectId

public abstract WritableObjectId findObjectId(Object forPojo,
                                              ObjectIdGenerator<?> generatorType)
Method called to find the Object Id for given POJO, if one has been generated. Will always return a non-null Object; contents vary depending on whether an Object Id already exists or not.


findValueSerializer

public JsonSerializer<Object> findValueSerializer(Class<?> valueType,
                                                  BeanProperty property)
                                           throws JsonMappingException
Method called to get hold of a serializer for a value of given type; or if no such serializer can be found, a default handler (which may do a best-effort generic serialization or just simply throw an exception when invoked).

Note: this method is only called for non-null values; not for keys or null values. For these, check out other accessor methods.

Note that starting with version 1.5, serializers should also be type-aware if they handle polymorphic types. That means that it may be necessary to also use a TypeSerializer based on declared (static) type being serializer (whereas actual data may be serialized using dynamic type)

Throws:
JsonMappingException - if there are fatal problems with accessing suitable serializer; including that of not finding any serializer

findValueSerializer

public JsonSerializer<Object> findValueSerializer(JavaType valueType,
                                                  BeanProperty property)
                                           throws JsonMappingException
Similar to findValueSerializer(Class,BeanProperty), but takes full generics-aware type instead of raw class. This is necessary for accurate handling of external type information, to handle polymorphic types.

Parameters:
property - When creating secondary serializers, property for which serializer is needed: annotations of the property (or bean that contains it) may be checked to create contextual serializers.
Throws:
JsonMappingException

findTypedValueSerializer

public JsonSerializer<Object> findTypedValueSerializer(Class<?> valueType,
                                                       boolean cache,
                                                       BeanProperty property)
                                                throws JsonMappingException
Method called to locate regular serializer, matching type serializer, and if both found, wrap them in a serializer that calls both in correct sequence. This method is currently only used for root-level serializer handling to allow for simpler caching. A call can always be replaced by equivalent calls to access serializer and type serializer separately.

Parameters:
valueType - Type for purpose of locating a serializer; usually dynamic runtime type, but can also be static declared type, depending on configuration
cache - Whether resulting value serializer should be cached or not; this is just a hint
property - When creating secondary serializers, property for which serializer is needed: annotations of the property (or bean that contains it) may be checked to create contextual serializers.
Throws:
JsonMappingException

findTypedValueSerializer

public JsonSerializer<Object> findTypedValueSerializer(JavaType valueType,
                                                       boolean cache,
                                                       BeanProperty property)
                                                throws JsonMappingException
Method called to locate regular serializer, matching type serializer, and if both found, wrap them in a serializer that calls both in correct sequence. This method is currently only used for root-level serializer handling to allow for simpler caching. A call can always be replaced by equivalent calls to access serializer and type serializer separately.

Parameters:
valueType - Declared type of value being serialized (which may not be actual runtime type); used for finding both value serializer and type serializer to use for adding polymorphic type (if any)
cache - Whether resulting value serializer should be cached or not; this is just a hint
property - When creating secondary serializers, property for which serializer is needed: annotations of the property (or bean that contains it) may be checked to create contextual serializers.
Throws:
JsonMappingException

findKeySerializer

public JsonSerializer<Object> findKeySerializer(JavaType keyType,
                                                BeanProperty property)
                                         throws JsonMappingException
Method called to get the serializer to use for serializing non-null Map keys. Separation from regular findValueSerializer(java.lang.Class, com.fasterxml.jackson.databind.BeanProperty) method is because actual write method must be different (@link JsonGenerator#writeFieldName}; but also since behavior for some key types may differ.

Note that the serializer itself can be called with instances of any Java object, but not nulls.

Throws:
JsonMappingException

getDefaultNullKeySerializer

public JsonSerializer<Object> getDefaultNullKeySerializer()
Since:
2.0

getDefaultNullValueSerializer

public JsonSerializer<Object> getDefaultNullValueSerializer()
Since:
2.0

findNullKeySerializer

public JsonSerializer<Object> findNullKeySerializer(JavaType serializationType,
                                                    BeanProperty property)
                                             throws JsonMappingException
Method called to find a serializer to use for null values for given declared type. Note that type is completely based on declared type, since nulls in Java have no type and thus runtime type can not be determined.

Throws:
JsonMappingException
Since:
2.0

findNullValueSerializer

public JsonSerializer<Object> findNullValueSerializer(BeanProperty property)
                                               throws JsonMappingException
Method called to get the serializer to use for serializing null property values.

Default implementation simply calls getDefaultNullValueSerializer(); can be overridden to add custom null serialization for properties of certain type or name.

Throws:
JsonMappingException
Since:
2.0

getUnknownTypeSerializer

public JsonSerializer<Object> getUnknownTypeSerializer(Class<?> unknownType)
Method called to get the serializer to use if provider can not determine an actual type-specific serializer to use; typically when none of SerializerFactory instances are able to construct a serializer.

Typically, returned serializer will throw an exception, although alternatively ToStringSerializer could be returned as well.

Parameters:
unknownType - Type for which no serializer is found

serializerInstance

public abstract JsonSerializer<Object> serializerInstance(Annotated annotated,
                                                          Object serDef)
                                                   throws JsonMappingException
Method that can be called to construct and configure serializer instance, either given a Class to instantiate (with default constructor), or an uninitialized serializer instance. Either way, serialize will be properly resolved (via ResolvableSerializer) and/or contextualized (via ContextualSerializer) as necessary.

Parameters:
annotated - Annotated entity that contained definition
serDef - Serializer definition: either an instance or class
Throws:
JsonMappingException

objectIdGeneratorInstance

public abstract ObjectIdGenerator<?> objectIdGeneratorInstance(Annotated annotated,
                                                               ObjectIdInfo objectIdInfo)
                                                        throws JsonMappingException
Throws:
JsonMappingException

defaultSerializeValue

public final void defaultSerializeValue(Object value,
                                        JsonGenerator jgen)
                                 throws IOException,
                                        JsonProcessingException
Convenience method that will serialize given value (which can be null) using standard serializer locating functionality. It can be called for all values including field and Map values, but usually field values are best handled calling defaultSerializeField(java.lang.String, java.lang.Object, com.fasterxml.jackson.core.JsonGenerator) instead.

Throws:
IOException
JsonProcessingException

defaultSerializeField

public final void defaultSerializeField(String fieldName,
                                        Object value,
                                        JsonGenerator jgen)
                                 throws IOException,
                                        JsonProcessingException
Convenience method that will serialize given field with specified value. Value may be null. Serializer is done using the usual null) using standard serializer locating functionality.

Throws:
IOException
JsonProcessingException

defaultSerializeDateValue

public final void defaultSerializeDateValue(long timestamp,
                                            JsonGenerator jgen)
                                     throws IOException,
                                            JsonProcessingException
Method that will handle serialization of Date(-like) values, using SerializationConfig settings to determine expected serialization behavior. Note: date here means "full" date, that is, date AND time, as per Java convention (and not date-only values like in SQL)

Throws:
IOException
JsonProcessingException

defaultSerializeDateValue

public final void defaultSerializeDateValue(Date date,
                                            JsonGenerator jgen)
                                     throws IOException,
                                            JsonProcessingException
Method that will handle serialization of Date(-like) values, using SerializationConfig settings to determine expected serialization behavior. Note: date here means "full" date, that is, date AND time, as per Java convention (and not date-only values like in SQL)

Throws:
IOException
JsonProcessingException

defaultSerializeDateKey

public void defaultSerializeDateKey(long timestamp,
                                    JsonGenerator jgen)
                             throws IOException,
                                    JsonProcessingException
Method that will handle serialization of Dates used as Map keys, based on SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS value (and if using textual representation, configured date format)

Throws:
IOException
JsonProcessingException

defaultSerializeDateKey

public void defaultSerializeDateKey(Date date,
                                    JsonGenerator jgen)
                             throws IOException,
                                    JsonProcessingException
Method that will handle serialization of Dates used as Map keys, based on SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS value (and if using textual representation, configured date format)

Throws:
IOException
JsonProcessingException

defaultSerializeNull

public final void defaultSerializeNull(JsonGenerator jgen)
                                throws IOException,
                                       JsonProcessingException
Throws:
IOException
JsonProcessingException

_reportIncompatibleRootType

protected void _reportIncompatibleRootType(Object value,
                                           JavaType rootType)
                                    throws IOException,
                                           JsonProcessingException
Throws:
IOException
JsonProcessingException

_findExplicitUntypedSerializer

protected JsonSerializer<Object> _findExplicitUntypedSerializer(Class<?> runtimeType,
                                                                BeanProperty property)
Method that will try to find a serializer, either from cache or by constructing one; but will not return an "unknown" serializer if this can not be done but rather returns null.

Returns:
Serializer if one can be found, null if not.

_createAndCacheUntypedSerializer

protected JsonSerializer<Object> _createAndCacheUntypedSerializer(Class<?> type,
                                                                  BeanProperty property)
                                                           throws JsonMappingException
Method that will try to construct a value serializer; and if one is successfully created, cache it for reuse.

Throws:
JsonMappingException

_createAndCacheUntypedSerializer

protected JsonSerializer<Object> _createAndCacheUntypedSerializer(JavaType type,
                                                                  BeanProperty property)
                                                           throws JsonMappingException
Throws:
JsonMappingException

_createUntypedSerializer

protected JsonSerializer<Object> _createUntypedSerializer(JavaType type,
                                                          BeanProperty property)
                                                   throws JsonMappingException
Throws:
JsonMappingException

_handleContextualResolvable

protected JsonSerializer<Object> _handleContextualResolvable(JsonSerializer<?> ser,
                                                             BeanProperty property)
                                                      throws JsonMappingException
Helper method called to resolve and contextualize given serializer, if and as necessary.

Throws:
JsonMappingException

_handleResolvable

protected JsonSerializer<Object> _handleResolvable(JsonSerializer<?> ser)
                                            throws JsonMappingException
Throws:
JsonMappingException

_handleContextual

protected JsonSerializer<Object> _handleContextual(JsonSerializer<?> ser,
                                                   BeanProperty property)
                                            throws JsonMappingException
Throws:
JsonMappingException

_dateFormat

protected final DateFormat _dateFormat()


Copyright © 2012 fasterxml.com. All Rights Reserved.