Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package com.fasterxml.jackson.databind.ser;
  
  import java.util.HashMap;
  
Base bean property handler class, which implements common parts of reflection-based functionality for accessing a property value and serializing it.

Note that current design tries to keep instances immutable (semi-functional style); mostly because these instances are exposed to application code and this is to reduce likelihood of data corruption and synchronization issues.

 
 public class BeanPropertyWriter
     implements BeanProperty
 {
    
Marker object used to indicate "do not serialize if empty"
 
     public final static Object MARKER_FOR_EMPTY = new Object();
     
     /*
     /**********************************************************
     /* Settings for accessing property value to serialize
     /**********************************************************
      */

    
Member (field, method) that represents property and allows access to associated annotations.
 
     protected final AnnotatedMember _member;

    
Annotations from context (most often, class that declares property, or in case of sub-class serializer, from that sub-class)
 
     protected final Annotations _contextAnnotations;
    
    
Type property is declared to have, either in class definition or associated annotations.
 
     protected final JavaType _declaredType;
    
    
Accessor method used to get property value, for method-accessible properties. Null if and only if _field is null.
 
     protected final Method _accessorMethod;
    
    
Field that contains the property value for field-accessible properties. Null if and only if _accessorMethod is null.
 
     protected final Field _field;
     
     /*
     /**********************************************************
     /* Opaque internal data that bean serializer factory and
     /* bean serializers can add.
     /**********************************************************
      */
 
     protected HashMap<Object,Object_internalSettings;
     
     /*
     /**********************************************************
     /* Serialization settings
     /**********************************************************
      */
    
    
Logical name of the property; will be used as the field name under which value for the property is written.
 
     protected final SerializedString _name;

    
Wrapper name to use for this element, if any

Since:
2.2
    protected final PropertyName _wrapperName;
    
    
Type to use for locating serializer; normally same as return type of the accessor method, but may be overridden by annotations.
    protected final JavaType _cfgSerializationType;

    
Serializer to use for writing out the value: null if it can not be known statically; non-null if it can.
    protected JsonSerializer<Object_serializer;

    
Serializer used for writing out null values, if any: if null, null values are to be suppressed.
    protected JsonSerializer<Object_nullSerializer;
    
    
In case serializer is not known statically (i.e. _serializer is null), we will use a lookup structure for storing dynamically resolved mapping from type(s) to serializer(s).
    protected PropertySerializerMap _dynamicSerializers;

    
Whether null values are to be suppressed (nothing written out if value is null) or not.
    protected final boolean _suppressNulls;
    
    
Value that is considered default value of the property; used for default-value-suppression if enabled.
    protected final Object _suppressableValue;

    
Alternate set of property writers used when view-based filtering is available for the Bean.
    protected final Class<?>[] _includeInViews;

    
If property being serialized needs type information to be included this is the type serializer to use. Declared type (possibly augmented with annotations) of property is used for determining exact mechanism to use (compared to actual runtime type used for serializing actual state).
    protected TypeSerializer _typeSerializer;
    
    
Base type of the property, if the declared type is "non-trivial"; meaning it is either a structured type (collection, map, array), or parameterized. Used to retain type information about contained type, which is mostly necessary if type meta-data is to be included.
    protected JavaType _nonTrivialBaseType;

    
Whether value of this property has been marked as required. Retained since it will be needed when traversing type hierarchy for producing schemas (and other similar tasks); currently not used for serialization.

Since:
2.2
    protected final boolean _isRequired;
    
    /*
    /**********************************************************
    /* Construction, configuration
    /**********************************************************
     */
    
    @SuppressWarnings("unchecked")
            AnnotatedMember memberAnnotations contextAnnotations,
            JavaType declaredType,
            JsonSerializer<?> serTypeSerializer typeSerJavaType serType,
            boolean suppressNullsObject suppressableValue)
    {
        
         = member;
         = contextAnnotations;
         = new SerializedString(propDef.getName());
         = propDef.getWrapperName();
         = declaredType;
         = (JsonSerializer<Object>) ser;
         = (ser == null) ? PropertySerializerMap.emptyMap() : null;
         = typeSer;
         = serType;
         = propDef.isRequired();
        if (member instanceof AnnotatedField) {
             = null;
             = (Fieldmember.getMember();
        } else if (member instanceof AnnotatedMethod) {
             = (Methodmember.getMember();
             = null;
        } else {
            throw new IllegalArgumentException("Can not pass member of type "+member.getClass().getName());
        }
         = suppressNulls;
         = suppressableValue;
         = propDef.findViews();
        // this will be resolved later on, unless nulls are to be suppressed
         = null;
    }

    
"Copy constructor" to be used by filtering sub-classes
    protected BeanPropertyWriter(BeanPropertyWriter base) {
        this(basebase._name);
    }
    {
         = name;
         = base._wrapperName;
         = base._member;
         = base._contextAnnotations;
         = base._declaredType;
         = base._accessorMethod;
         = base._field;
         = base._serializer;
         = base._nullSerializer;
        // one more thing: copy internal settings, if any (since 1.7)
        if (base._internalSettings != null) {
             = new HashMap<Object,Object>(base._internalSettings);
        }
         = base._cfgSerializationType;
         = base._dynamicSerializers;
         = base._suppressNulls;
         = base._suppressableValue;
         = base._includeInViews;
         = base._typeSerializer;
         = base._nonTrivialBaseType;
         = base._isRequired;
    }
    public BeanPropertyWriter rename(NameTransformer transformer) {
        String newName = transformer.transform(.getValue());
        if (newName.equals(.toString())) {
            return this;
        }
        return new BeanPropertyWriter(thisnew SerializedString(newName));
    }
    
    
Method called to assign value serializer for property

Since:
2.0
    public void assignSerializer(JsonSerializer<Objectser)
    {
        // may need to disable check in future?
        if ( != null &&  != ser) {
            throw new IllegalStateException("Can not override serializer");
        }
         = ser;
    }

    
Method called to assign null value serializer for property

Since:
2.0
    public void assignNullSerializer(JsonSerializer<ObjectnullSer)
    {
        // may need to disable check in future?
        if ( != null &&  != nullSer) {
            throw new IllegalStateException("Can not override null serializer");
        }
         = nullSer;
    }
    
    
Method called create an instance that handles details of unwrapping contained value.
        return new UnwrappingBeanPropertyWriter(thisunwrapper);
    }

    
Method called to define type to consider as "non-trivial" basetype, needed for dynamic serialization resolution for complex (usually container) types
    public void setNonTrivialBaseType(JavaType t) {
         = t;
    }
    /*
    /**********************************************************
    /* BeanProperty impl
    /**********************************************************
     */
    
    @Override
    public String getName() {
        return .getValue();
    }
    @Override
    public JavaType getType() {
        return ;
    }
    @Override
    public PropertyName getWrapperName() {
        return ;
    }
    @Override
    public boolean isRequired() {
        return ;
    }
    
    @Override
    public <A extends Annotation> A getAnnotation(Class<A> acls) {
        return .getAnnotation(acls);
    }
    @Override
    public <A extends Annotation> A getContextAnnotation(Class<A> acls) {
        return .get(acls);
    }
    @Override
    public AnnotatedMember getMember() {
        return ;
    }
    @Override
    public void depositSchemaProperty(JsonObjectFormatVisitor objectVisitor)
        throws JsonMappingException
    {
        if (objectVisitor != null) {
            if (isRequired()) {
                objectVisitor.property(this); 
            } else {
                objectVisitor.optionalProperty(this);
            }
        }
    }
    /*
    /**********************************************************
    /* Managing and accessing of opaque internal settings
    /* (used by extensions)
    /**********************************************************
     */
    
    
Method for accessing value of specified internal setting.

Returns:
Value of the setting, if any; null if none.
    public Object getInternalSetting(Object key)
    {
        if ( == null) {
            return null;
        }
        return .get(key);
    }
    
    
Method for setting specific internal setting to given value

Returns:
Old value of the setting, if any (null if none)
    public Object setInternalSetting(Object keyObject value)
    {
        if ( == null) {
             = new HashMap<Object,Object>();
        }
        return .put(keyvalue);
    }

    
Method for removing entry for specified internal setting.

Returns:
Existing value of the setting, if any (null if none)
    public Object removeInternalSetting(Object key)
    {
        Object removed = null;
        if ( != null) {
            removed = .remove(key);
            // to reduce memory usage, let's also drop the Map itself, if empty
            if (.size() == 0) {
                 = null;
            }
        }
        return removed;
    }
    
    /*
    /**********************************************************
    /* Accessors
    /**********************************************************
     */
    public SerializedString getSerializedName() { return ; }
    
    public boolean hasSerializer() { return  != null; }
    public boolean hasNullSerializer() { return  != null; }
    public boolean willSuppressNulls() { return ; }
    
    // Needed by BeanSerializer#getSchema
    public JsonSerializer<ObjectgetSerializer() {
        return ;
    }
    public JavaType getSerializationType() {
        return ;
    }
    public Class<?> getRawSerializationType() {
        return ( == null) ? null : .getRawClass();
    }
    
    public Class<?> getPropertyType() 
    {
        if ( != null) {
            return .getReturnType();
        }
        return .getType();
    }

    
Get the generic property type of this property writer.

Returns:
The property type, or null if not found.
    public Type getGenericPropertyType()
    {
        if ( != null) {
            return .getGenericReturnType();
        }
        return .getGenericType();
    }
    public Class<?>[] getViews() { return ; }

    

NOTE: due to introspection, this is a slow method to call and should never be called during actual serialization or filtering of the property. Rather it is needed for traversal needed for things like constructing JSON Schema instances.

Deprecated:
since 2.2, use isRequired() instead.
Since:
2.1
    @Deprecated
    protected boolean isRequired(AnnotationIntrospector intr) {
        return ;
    }
    /*
    /**********************************************************
    /* Legacy support for JsonFormatVisitable
    /**********************************************************
     */

    
Attempt to add the output of the given BeanPropertyWriter in the given com.fasterxml.jackson.databind.node.ObjectNode. Otherwise, add the default schema com.fasterxml.jackson.databind.JsonNode in place of the writer's output

Parameters:
propertiesNode Node which the given property would exist within
provider Provider that can be used for accessing dynamic aspects of serialization processing BeanPropertyFilter.depositSchemaProperty(com.fasterxml.jackson.databind.ser.BeanPropertyWriter,com.fasterxml.jackson.databind.node.ObjectNode,com.fasterxml.jackson.databind.SerializerProvider)
Since:
2.1
    @SuppressWarnings("deprecation")
    public void depositSchemaProperty(ObjectNode propertiesNodeSerializerProvider provider)
        throws JsonMappingException
    {
        JavaType propType = getSerializationType();
        // 03-Dec-2010, tatu: SchemaAware REALLY should use JavaType, but alas it doesn't...
        Type hint = (propType == null) ? getGenericPropertyType() : propType.getRawClass();
        JsonNode schemaNode;
        // Maybe it already has annotated/statically configured serializer?
        JsonSerializer<Objectser = getSerializer();
        if (ser == null) { // nope
            Class<?> serType = getRawSerializationType();
            if (serType == null) {
                serType = getPropertyType();
            }
            ser = provider.findValueSerializer(serTypethis);
        }
        boolean isOptional = !isRequired();
        if (ser instanceof SchemaAware) {
            schemaNode =  ((SchemaAwareser).getSchema(providerhintisOptional) ;
        } else {  
            schemaNode = com.fasterxml.jackson.databind.jsonschema.JsonSchema.getDefaultSchemaNode(); 
        }
        propertiesNode.put(getName(), schemaNode);
    }
    
    /*
    /**********************************************************
    /* Serialization functionality
    /**********************************************************
     */

    
Method called to access property that this bean stands for, from within given bean, and to serialize it as a JSON Object field using appropriate serializer.
    public void serializeAsField(Object beanJsonGenerator jgenSerializerProvider prov)
        throws Exception
    {
        Object value = get(bean);
        // Null handling is bit different, check that first
        if (value == null) {
            if ( != null) {
                jgen.writeFieldName();
                .serialize(nulljgenprov);
            }
            return;
        }
        // then find serializer to use
        JsonSerializer<Objectser = ;
        if (ser == null) {
            Class<?> cls = value.getClass();
            PropertySerializerMap map = ;
            ser = map.serializerFor(cls);
            if (ser == null) {
                ser = _findAndAddDynamic(mapclsprov);
            }
        }
        // and then see if we must suppress certain values (default, empty)
        if ( != null) {
            if ( == ) {
                if (ser.isEmpty(value)) {
                    return;
                }
            } else if (.equals(value)) {
                return;
            }
        }
        // For non-nulls: simple check for direct cycles
        if (value == bean) {
            _handleSelfReference(beanser);
        }
        jgen.writeFieldName();
        if ( == null) {
            ser.serialize(valuejgenprov);
        } else {
            ser.serializeWithType(valuejgenprov);
        }
    }

    
Alternative to serializeAsField(java.lang.Object,com.fasterxml.jackson.core.JsonGenerator,com.fasterxml.jackson.databind.SerializerProvider) that is used when a POJO is serialized as JSON Array; the difference is that no field names are written.

Since:
2.1
    public void serializeAsColumn(Object beanJsonGenerator jgenSerializerProvider prov)
        throws Exception
    {
        Object value = get(bean);
        if (value == null) { // nulls need specialized handling
            if ( != null) {
                .serialize(nulljgenprov);
            } else { // can NOT suppress entries in tabular output
                jgen.writeNull();
            }
        }
        // otherwise find serializer to use
        JsonSerializer<Objectser = ;
        if (ser == null) {
            Class<?> cls = value.getClass();
            PropertySerializerMap map = ;
            ser = map.serializerFor(cls);
            if (ser == null) {
                ser = _findAndAddDynamic(mapclsprov);
            }
        }
        // and then see if we must suppress certain values (default, empty)
        if ( != null) {
            if ( == ) {
                if (ser.isEmpty(value)) { // can NOT suppress entries in tabular output
                    serializeAsPlaceholder(beanjgenprov);
                    return;
                }
            } else if (.equals(value)) { // can NOT suppress entries in tabular output
                serializeAsPlaceholder(beanjgenprov);
                return;
            }
        }
        // For non-nulls: simple check for direct cycles
        if (value == bean) {
            _handleSelfReference(beanser);
        }
        if ( == null) {
            ser.serialize(valuejgenprov);
        } else {
            ser.serializeWithType(valuejgenprov);
        }
    }

    
Method called to serialize a placeholder used in tabular output when real value is not to be included (is filtered out), but when we need an entry so that field indexes will not be off. Typically this should output null or empty String, depending on datatype.

Since:
2.1
    public void serializeAsPlaceholder(Object beanJsonGenerator jgenSerializerProvider prov)
        throws Exception
    {
        if ( != null) {
            .serialize(nulljgenprov);
        } else {
            jgen.writeNull();
        }
    }
    
    /*
    /**********************************************************
    /* Helper methods
    /**********************************************************
     */
    
            Class<?> typeSerializerProvider providerthrows JsonMappingException
    {
        if ( != null) {
            JavaType t = provider.constructSpecializedType(type);
            result = map.findAndAddSerializer(tproviderthis);
        } else {
            result = map.findAndAddSerializer(typeproviderthis);
        }
        // did we get a new map of serializers? If so, start using it
        if (map != result.map) {
             = result.map;
        }
        return result.serializer;
    }
    
    
Method that can be used to access value of the property this Object describes, from given bean instance.

Note: method is final as it should not need to be overridden -- rather, calling method(s) (serializeAsField(java.lang.Object,com.fasterxml.jackson.core.JsonGenerator,com.fasterxml.jackson.databind.SerializerProvider)) should be overridden to change the behavior

    public final Object get(Object beanthrows Exception
    {
        if ( != null) {
            return .invoke(bean);
        }
        return .get(bean);
    }
    protected void _handleSelfReference(Object beanJsonSerializer<?> ser)
        throws JsonMappingException
    {
        /* 05-Feb-2012, tatu: Usually a problem, but NOT if we are handling
         *    object id; this may be the case for BeanSerializers at least.
         */
        if (ser.usesObjectId()) {
            return;
        }
        throw new JsonMappingException("Direct self-reference leading to cycle");
    }
    @Override
    public String toString()
    {
        StringBuilder sb = new StringBuilder(40);
        sb.append("property '").append(getName()).append("' (");
        if ( != null) {
            sb.append("via method ").append(.getDeclaringClass().getName()).append("#").append(.getName());
        } else {
            sb.append("field \"").append(.getDeclaringClass().getName()).append("#").append(.getName());
        }
        if ( == null) {
            sb.append(", no static serializer");
        } else {
            sb.append(", static serializer of type "+.getClass().getName());
        }
        sb.append(')');
        return sb.toString();
    }
New to GrepCode? Check out our FAQ X