Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package com.fasterxml.jackson.databind.ser;
  
  import java.util.*;
  
  
 
Standard implementation used by com.fasterxml.jackson.databind.ObjectMapper: adds methods only exposed to com.fasterxml.jackson.databind.ObjectMapper, as well as constructors.

Note that class is abstract just because it does not define createInstance(com.fasterxml.jackson.databind.SerializationConfig,com.fasterxml.jackson.databind.ser.SerializerFactory) method.

Also note that all custom com.fasterxml.jackson.databind.SerializerProvider implementations must sub-class this class: com.fasterxml.jackson.databind.ObjectMapper requires this type, not basic provider type.

 
 public abstract class DefaultSerializerProvider
     extends SerializerProvider
     implements java.io.Serializable // since 2.1; only because ObjectWriter needs it
 {
     private static final long serialVersionUID = 1L;
 
     /*
     /**********************************************************
     /* State, for non-blueprint instances: Object Id handling
     /**********************************************************
      */

    
Per-serialization map Object Ids that have seen so far, iff Object Id handling is enabled.
 
     protected transient IdentityHashMap<ObjectWritableObjectId_seenObjectIds;
     
     protected transient ArrayList<ObjectIdGenerator<?>> _objectIdGenerators;
     
     /*
     /**********************************************************
     /* Life-cycle
     /**********************************************************
      */
 
     protected DefaultSerializerProvider() { super(); }
 
             SerializationConfig config,SerializerFactory f) {
         super(srcconfigf);
     }
 
     /*
     /**********************************************************
     /* Extended API: methods that ObjectMapper will call
     /**********************************************************
      */

    
Overridable method, used to create a non-blueprint instances from the blueprint. This is needed to retain state during serialization.
 
     public abstract DefaultSerializerProvider createInstance(SerializationConfig config,
             SerializerFactory jsf);
    
    
The method to be called by com.fasterxml.jackson.databind.ObjectMapper and com.fasterxml.jackson.databind.ObjectWriter for serializing given value, using serializers that this provider has access to (via caching and/or creating new serializers as need be).
 
     public void serializeValue(JsonGenerator jgenObject value)
         throws IOExceptionJsonGenerationException
     {
         JsonSerializer<Objectser;
         final boolean wrap;
 
         if (value == null) { // no type provided; must just use the default null serializer
             ser = getDefaultNullValueSerializer();
             wrap = false// no name to use for wrapping; can't do!
         } else {
             Class<?> cls = value.getClass();
             // true, since we do want to cache root-level typed serializers (ditto for null property)
             ser = findTypedValueSerializer(clstruenull);
            // Ok: should we wrap result in an additional property ("root name")?
            String rootName = .getRootName();
            if (rootName == null) { // not explicitly specified
                // [JACKSON-163]
                wrap = .isEnabled(.);
                if (wrap) {
                    jgen.writeStartObject();
                    jgen.writeFieldName(.findRootName(value.getClass(), ));
                }
            } else if (rootName.length() == 0) {
                wrap = false;
            } else { // [JACKSON-764]
                // empty String means explicitly disabled; non-empty that it is enabled
                wrap = true;
                jgen.writeStartObject();
                jgen.writeFieldName(rootName);
            }
        }
        try {
            ser.serialize(valuejgenthis);
            if (wrap) {
                jgen.writeEndObject();
            }
        } catch (IOException ioe) { // As per [JACKSON-99], pass IOException and subtypes as-is
            throw ioe;
        } catch (Exception e) { // but wrap RuntimeExceptions, to get path information
            String msg = e.getMessage();
            if (msg == null) {
                msg = "[no message for "+e.getClass().getName()+"]";
            }
            throw new JsonMappingException(msge);
        }
    }

    
The method to be called by com.fasterxml.jackson.databind.ObjectMapper and com.fasterxml.jackson.databind.ObjectWriter for serializing given value (assumed to be of specified root type, instead of runtime type of value), using serializers that this provider has access to (via caching and/or creating new serializers as need be),

Parameters:
rootType Type to use for locating serializer to use, instead of actual runtime type. Must be actual type, or one of its super types
    public void serializeValue(JsonGenerator jgenObject valueJavaType rootType)
        throws IOExceptionJsonGenerationException
    {
        final boolean wrap;
        JsonSerializer<Objectser;
        if (value == null) {
            ser = getDefaultNullValueSerializer();
            wrap = false;
        } else {
            // Let's ensure types are compatible at this point
            if (!rootType.getRawClass().isAssignableFrom(value.getClass())) {
                _reportIncompatibleRootType(valuerootType);
            }
            // root value, not reached via property:
            ser = findTypedValueSerializer(rootTypetruenull);
            // [JACKSON-163]
            wrap = .isEnabled(.);
            if (wrap) {
                jgen.writeStartObject();
                jgen.writeFieldName(.findRootName(rootType));
            }
        }
        try {
            ser.serialize(valuejgenthis);
            if (wrap) {
                jgen.writeEndObject();
            }
        } catch (IOException ioe) { // no wrapping for IO (and derived)
            throw ioe;
        } catch (Exception e) { // but others do need to be, to get path etc
            String msg = e.getMessage();
            if (msg == null) {
                msg = "[no message for "+e.getClass().getName()+"]";
            }
            throw new JsonMappingException(msge);
        }
    }

    
The method to be called by com.fasterxml.jackson.databind.ObjectWriter for serializing given value (assumed to be of specified root type, instead of runtime type of value), when it may know specific com.fasterxml.jackson.databind.JsonSerializer to use.

Parameters:
rootType Type to use for locating serializer to use, instead of actual runtime type, if no serializer is passed
ser Root Serializer to use, if not null
Since:
2.1
    public void serializeValue(JsonGenerator jgenObject valueJavaType rootType,
            JsonSerializer<Objectser)
        throws IOExceptionJsonGenerationException
    {
        final boolean wrap;
        if (value == null) {
            ser = getDefaultNullValueSerializer();
            wrap = false;
        } else {
            // Let's ensure types are compatible at this point
            if (rootType != null) {
                if (!rootType.getRawClass().isAssignableFrom(value.getClass())) {
                    _reportIncompatibleRootType(valuerootType);
                }
            }
            // root value, not reached via property:
            if (ser == null) {
                ser = findTypedValueSerializer(rootTypetruenull);
            }
            wrap = .isEnabled(.);
            if (wrap) {
                jgen.writeStartObject();
                jgen.writeFieldName(.findRootName(rootType));
            }
        }
        try {
            ser.serialize(valuejgenthis);
            if (wrap) {
                jgen.writeEndObject();
            }
        } catch (IOException ioe) { // no wrapping for IO (and derived)
            throw ioe;
        } catch (Exception e) { // but others do need to be, to get path etc
            String msg = e.getMessage();
            if (msg == null) {
                msg = "[no message for "+e.getClass().getName()+"]";
            }
            throw new JsonMappingException(msge);
        }
    }
    
    
The method to be called by com.fasterxml.jackson.databind.ObjectMapper and com.fasterxml.jackson.databind.ObjectWriter to generate JSON schema for given type.

Parameters:
type The type for which to generate schema
    public JsonSchema generateJsonSchema(Class<?> type)
            throws JsonMappingException
        {
            if (type == null) {
                throw new IllegalArgumentException("A class must be provided");
            }
            /* no need for embedded type information for JSON schema generation (all
             * type information it needs is accessible via "untyped" serializer)
             */
            JsonSerializer<Objectser = findValueSerializer(typenull);
            JsonNode schemaNode = (ser instanceof SchemaAware) ?
                    ((SchemaAwareser).getSchema(thisnull) : 
                    JsonSchema.getDefaultSchemaNode();
            if (!(schemaNode instanceof ObjectNode)) {
                throw new IllegalArgumentException("Class " + type.getName() +
                        " would not be serialized as a JSON object and therefore has no schema");
            }
            return new JsonSchema((ObjectNodeschemaNode);
        }
    
    
The method to be called by com.fasterxml.jackson.databind.ObjectMapper and com.fasterxml.jackson.databind.ObjectWriter to to expose the format of the given to to the given visitor

Parameters:
javaType The type for which to generate format
visitor the visitor to accept the format
    public void acceptJsonFormatVisitor(JavaType javaTypeJsonFormatVisitorWrapper visitor)
        throws JsonMappingException
    {
        if (javaType == null) {
            throw new IllegalArgumentException("A class must be provided");
        }
        /* no need for embedded type information for JSON schema generation (all
         * type information it needs is accessible via "untyped" serializer)
         */
        findValueSerializer(javaTypenull).acceptJsonFormatVisitor(visitorjavaType);
    }
    
    
Method that can be called to see if this serializer provider can find a serializer for an instance of given class.

Note that no Exceptions are thrown, including unchecked ones: implementations are to swallow exceptions if necessary.

    public boolean hasSerializerFor(Class<?> cls) {
        return _findExplicitUntypedSerializer(cls) != null;
    }
    /*
    /********************************************************
    /* Access to caching details
    /********************************************************
     */

    
Method that can be used to determine how many serializers this provider is caching currently (if it does caching: default implementation does) Exact count depends on what kind of serializers get cached; default implementation caches all serializers, including ones that are eagerly constructed (for optimal access speed)

The main use case for this method is to allow conditional flushing of serializer cache, if certain number of entries is reached.

    public int cachedSerializersCount() {
        return .size();
    }

    
Method that will drop all serializers currently cached by this provider. This can be used to remove memory usage (in case some serializers are only used once or so), or to force re-construction of serializers after configuration changes for mapper than owns the provider.
    public void flushCachedSerializers() {
        .flush();
    }
    /*
    /**********************************************************
    /* Object Id handling
    /**********************************************************
     */
    @Override
            ObjectIdInfo objectIdInfo)
        throws JsonMappingException
    {
        Class<?> implClass = objectIdInfo.getGeneratorType();
        ObjectIdGenerator<?> gen = (hi == null) ? null : hi.objectIdGeneratorInstance(annotatedimplClass);
        if (gen == null) {
            gen = (ObjectIdGenerator<?>) ClassUtil.createInstance(implClass,
                    .canOverrideAccessModifiers());
        }
        return gen.forScope(objectIdInfo.getScope());
    }
    
    @Override
    public WritableObjectId findObjectId(Object forPojo,
            ObjectIdGenerator<?> generatorType)
    {
        if ( == null) {
             = new IdentityHashMap<Object,WritableObjectId>();
        } else {
            WritableObjectId oid = .get(forPojo);
            if (oid != null) {
                return oid;
            }
        }
        // Not seen yet; must add an entry, return it. For that, we need generator
        ObjectIdGenerator<?> generator = null;
        
        if ( == null) {
             = new ArrayList<ObjectIdGenerator<?>>(8);
        } else {
            for (int i = 0, len = .size(); i < len; ++i) {
                ObjectIdGenerator<?> gen = .get(i);
                if (gen.canUseFor(generatorType)) {
                    generator = gen;
                    break;
                }
            }
        }
        if (generator == null) {
            generator = generatorType.newForSerialization(this);
            .add(generator);
        }
        WritableObjectId oid = new WritableObjectId(generator);
        .put(forPojooid);
        return oid;
    }
    /*
    /**********************************************************
    /* Factory method impls
    /**********************************************************
     */
    
    @Override
            Object serDef)
        throws JsonMappingException
    
    {
        if (serDef == null) {
            return null;
        }
        JsonSerializer<?> ser;
        
        if (serDef instanceof JsonSerializer) {
            ser = (JsonSerializer<?>) serDef;
        } else {
            /* Alas, there's no way to force return type of "either class
             * X or Y" -- need to throw an exception after the fact
             */
            if (!(serDef instanceof Class)) {
                throw new IllegalStateException("AnnotationIntrospector returned serializer definition of type "
                        +serDef.getClass().getName()+"; expected type JsonSerializer or Class<JsonSerializer> instead");
            }
            Class<?> serClass = (Class<?>)serDef;
            // there are some known "no class" markers to consider too:
            if (serClass == JsonSerializer.None.class || serClass == NoClass.class) {
                return null;
            }
            if (!JsonSerializer.class.isAssignableFrom(serClass)) {
                throw new IllegalStateException("AnnotationIntrospector returned Class "
                        +serClass.getName()+"; expected Class<JsonSerializer>");
            }
            HandlerInstantiator hi = .getHandlerInstantiator();
            ser = (hi == null) ? null : hi.serializerInstance(annotatedserClass);
            if (ser == null) {
                ser = (JsonSerializer<?>) ClassUtil.createInstance(serClass,
                        .canOverrideAccessModifiers());
            }
        }
        return (JsonSerializer<Object>) _handleResolvable(ser);
    }
    
    /*
    /**********************************************************
    /* Helper classes
    /**********************************************************
     */

    
Concrete implementation that defines factory method(s), defined as final.
    public final static class Impl extends DefaultSerializerProvider
    {
        private static final long serialVersionUID = 1L;
        public Impl() { super(); }
        protected Impl(SerializerProvider src,
                SerializationConfig config,SerializerFactory f) {
            super(srcconfigf);
        }
        @Override
        public Impl createInstance(SerializationConfig config,
                SerializerFactory jsf) {
            return new Impl(thisconfigjsf);
        }
    }
New to GrepCode? Check out our FAQ X