Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package com.fasterxml.jackson.databind.ser.std;
  
  import java.util.HashSet;
  import java.util.Set;
  
 
 
Standard serializer used for java.lang.Enum types.

Based on StdScalarSerializer since the JSON value is scalar (String).

Author(s):
tatu
 
 public class EnumSerializer
     extends StdScalarSerializer<Enum<?>>
     implements ContextualSerializer
 {
    
This map contains pre-resolved values (since there are ways to customize actual String constants to use) to use as serializations.
 
     protected final EnumValues _values;

    
Flag that is set if we statically know serialization choice between index and textual format (null if it needs to be dynamically checked).

Since:
2.1
 
     protected final Boolean _serializeAsIndex;
 
     /*
     /**********************************************************
     /* Construction, initialization
     /**********************************************************
      */
    
    

Deprecated:
Since 2.1
 
     @Deprecated
     public EnumSerializer(EnumValues v) {
         this(vnull);
     }
 
     public EnumSerializer(EnumValues vBoolean serializeAsIndex)
     {
         super(Enum.classfalse);
          = v;
          = serializeAsIndex;
     }
    
    
Factory method used by com.fasterxml.jackson.databind.ser.BasicSerializerFactory for constructing serializer instance of Enum types.

Since:
2.1
 
     public static EnumSerializer construct(Class<Enum<?>> enumClassSerializationConfig config,
             BeanDescription beanDescJsonFormat.Value format)
     {
         // [JACKSON-212]: If toString() is to be used instead, leave EnumValues null
         AnnotationIntrospector intr = config.getAnnotationIntrospector();
             ? EnumValues.constructFromToString(enumClassintr) : EnumValues.constructFromName(enumClassintr);
         Boolean serializeAsIndex = _isShapeWrittenUsingIndex(enumClassformattrue);
         return new EnumSerializer(vserializeAsIndex);
     }
    
    

Deprecated:
Since 2.1 use the variant that takes in format argument.
 
     @Deprecated
     public static EnumSerializer construct(Class<Enum<?>> enumClassSerializationConfig config,
             BeanDescription beanDesc)
     {
         return construct(enumClassconfigbeanDescbeanDesc.findExpectedFormat(null));
     }

    
To support some level of per-property configuration, we will need to make things contextual. We are limited to "textual vs index" choice here, however.
            BeanProperty propertythrows JsonMappingException
    {
        if (property != null) {
            JsonFormat.Value format = prov.getAnnotationIntrospector().findFormat((Annotatedproperty.getMember());
            if (format != null) {
                Boolean serializeAsIndex = _isShapeWrittenUsingIndex(property.getType().getRawClass(), formatfalse);
                if (serializeAsIndex != ) {
                    return new EnumSerializer(serializeAsIndex);
                }
            }
        }
        return this;
    }
    /*
    /**********************************************************
    /* Extended API for Jackson databind core
    /**********************************************************
     */
    
    public EnumValues getEnumValues() { return ; }
    /*
    /**********************************************************
    /* Actual serialization
    /**********************************************************
     */
    
    @Override
    public final void serialize(Enum<?> enJsonGenerator jgenSerializerProvider provider)
        throws IOExceptionJsonGenerationException
    {
        // [JACKSON-684]: serialize as index?
        if (_serializeAsIndex(provider)) {
            jgen.writeNumber(en.ordinal());
            return;
        }
        jgen.writeString(.serializedValueFor(en));
    }
    
    @Override
    public JsonNode getSchema(SerializerProvider providerType typeHint)
    {
        // [JACKSON-684]: serialize as index?
        if (_serializeAsIndex(provider)) {
            return createSchemaNode("integer"true);
        }
        ObjectNode objectNode = createSchemaNode("string"true);
        if (typeHint != null) {
            JavaType type = provider.constructType(typeHint);
            if (type.isEnumType()) {
                ArrayNode enumNode = objectNode.putArray("enum");
                for (SerializedString value : .values()) {
                    enumNode.add(value.getValue());
                }
            }
        }
        return objectNode;
    }
    
    @Override
    public void acceptJsonFormatVisitor(JsonFormatVisitorWrapper visitorJavaType typeHint)
    {
        // [JACKSON-684]: serialize as index?
    		visitor.expectIntegerFormat(typeHint);
    	} else {
    		JsonStringFormatVisitor stringVisitor = visitor.expectStringFormat(typeHint);
    		if (typeHint != null) {
    			if (typeHint.isEnumType()) {
    				Set<Stringenums = new HashSet<String>();
    				for (SerializedString value : .values()) {
    					enums.add(value.getValue());
    				}
    				stringVisitor.enumTypes(enums);
    			}
    		}
    	}
    }
    /*
    /**********************************************************
    /* Helper methods
    /**********************************************************
     */
    
    protected final boolean _serializeAsIndex(SerializerProvider provider)
    {
        if ( != null) {
            return .booleanValue();
        }
        return provider.isEnabled(.);
        
    }

    
Helper method called to check whether
    protected static Boolean _isShapeWrittenUsingIndex(Class<?> enumClass,
            JsonFormat.Value formatboolean fromClass)
    {
        JsonFormat.Shape shape = (format == null) ? null : format.getShape();
        if (shape == null) {
            return null;
        }
        if (shape == . || shape == .) { // i.e. "default", check dynamically
            return null;
        }
        if (shape == .) {
            return .;
        }
        if (shape.isNumeric()) {
            return .;
        }
        throw new IllegalArgumentException("Unsupported serialization shape ("+shape+") for Enum "+enumClass.getName()
                    +", not supported as "
                    + (fromClass"class" : "property")
                    +" annotation");
    }
New to GrepCode? Check out our FAQ X