Java Code Examples for com.fasterxml.jackson.annotation.JsonFormat#Value

The following examples show how to use com.fasterxml.jackson.annotation.JsonFormat#Value . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ArraySerializerBase.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public JsonSerializer<?> createContextual(SerializerProvider serializers,
        BeanProperty property) throws JsonMappingException
{
    Boolean unwrapSingle = null;

    // First: if we have a property, may have property-annotation overrides
    if (property != null) {
        JsonFormat.Value format = findFormatOverrides(serializers, property, handledType());
        if (format != null) {
            unwrapSingle = format.getFeature(JsonFormat.Feature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED);
            if (unwrapSingle != _unwrapSingle) {
                return _withResolved(property, unwrapSingle);
            }
        }
    }
    return this;
}
 
Example 2
Source File: JSR310StringParsableDeserializer.java    From jackson-modules-java8 with Apache License 2.0 6 votes vote down vote up
@Override
public JsonDeserializer<?> createContextual(DeserializationContext ctxt,
        BeanProperty property) throws JsonMappingException
{
    JsonFormat.Value format = findFormatOverrides(ctxt, property, handledType());
    JSR310StringParsableDeserializer deser = this;
    if (format != null) {
        if (format.hasLenient()) {
            Boolean leniency = format.getLenient();
            if (leniency != null) {
                deser = this.withLeniency(leniency);
            }
        }
    }
    return deser;
}
 
Example 3
Source File: DurationDeserializer.java    From jackson-modules-java8 with Apache License 2.0 6 votes vote down vote up
@Override
public JsonDeserializer<?> createContextual(DeserializationContext ctxt,
                                            BeanProperty property) throws JsonMappingException
{
    JsonFormat.Value format = findFormatOverrides(ctxt, property, handledType());
    DurationDeserializer deser = this;
    if (format != null) {
        if (format.hasLenient()) {
            Boolean leniency = format.getLenient();
            if (leniency != null) {
                deser = deser.withLeniency(leniency);
            }
        }
    }
    return deser;
}
 
Example 4
Source File: EnumSerializer.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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.
 */
@Override
public JsonSerializer<?> createContextual(SerializerProvider serializers,
        BeanProperty property) throws JsonMappingException
{
    JsonFormat.Value format = findFormatOverrides(serializers,
            property, handledType());
    if (format != null) {
        Class<?> type = handledType();
        Boolean serializeAsIndex = _isShapeWrittenUsingIndex(type,
                format, false, _serializeAsIndex);
        if (serializeAsIndex != _serializeAsIndex) {
            return new EnumSerializer(_values, serializeAsIndex);
        }
    }
    return this;
}
 
Example 5
Source File: StaticListSerializerBase.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public JsonSerializer<?> createContextual(SerializerProvider serializers,
        BeanProperty property)
    throws JsonMappingException
{
    JsonSerializer<?> ser = null;
    Boolean unwrapSingle = null;
    
    if (property != null) {
        final AnnotationIntrospector intr = serializers.getAnnotationIntrospector();
        AnnotatedMember m = property.getMember();
        if (m != null) {
            Object serDef = intr.findContentSerializer(m);
            if (serDef != null) {
                ser = serializers.serializerInstance(m, serDef);
            }
        }
    }
    JsonFormat.Value format = findFormatOverrides(serializers, property, handledType());
    if (format != null) {
        unwrapSingle = format.getFeature(JsonFormat.Feature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED);
    }
    // [databind#124]: May have a content converter
    ser = findContextualConvertingSerializer(serializers, property, ser);
    if (ser == null) {
        ser = serializers.findValueSerializer(String.class, property);
    }
    // Optimization: default serializer just writes String, so we can avoid a call:
    if (isDefaultSerializer(ser)) {
        if (unwrapSingle == _unwrapSingle) {
            return this;
        }
        return _withResolved(property, unwrapSingle);
    }
    // otherwise...
    // note: will never have TypeSerializer, because Strings are "natural" type
    return new CollectionSerializer(serializers.constructType(String.class),
            true, /*TypeSerializer*/ null, (JsonSerializer<Object>) ser);
}
 
Example 6
Source File: ConcreteBeanPropertyBase.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
@Deprecated
public final JsonFormat.Value findFormatOverrides(AnnotationIntrospector intr) {
    JsonFormat.Value f = null;
    if (intr != null) {
        AnnotatedMember member = getMember();
        if (member != null) {
            f = intr.findFormat(member);
        }
    }
    if (f == null) {
        f = EMPTY_FORMAT;
    }
    return f;
}
 
Example 7
Source File: Jackson2Parser.java    From typescript-generator with MIT License 5 votes vote down vote up
private static TypeProcessor createSpecificTypeProcessor() {
    return new TypeProcessor.Chain(
            new ExcludingTypeProcessor(Arrays.asList(JsonNode.class.getName())),
            new TypeProcessor() {
                @Override
                public TypeProcessor.Result processType(Type javaType, TypeProcessor.Context context) {
                    if (context.getTypeContext() instanceof Jackson2TypeContext) {
                        final Jackson2TypeContext jackson2TypeContext = (Jackson2TypeContext) context.getTypeContext();
                        if (!jackson2TypeContext.disableObjectIdentityFeature) {
                            final Type resultType = jackson2TypeContext.parser.processIdentity(javaType, jackson2TypeContext.beanPropertyWriter);
                            if (resultType != null) {
                                return context.withTypeContext(null).processType(resultType);
                            }
                        }
                        // Map.Entry
                        final Class<?> rawClass = Utils.getRawClassOrNull(javaType);
                        if (rawClass != null && Map.Entry.class.isAssignableFrom(rawClass)) {
                            final ObjectMapper objectMapper = jackson2TypeContext.parser.objectMapper;
                            final SerializationConfig serializationConfig = objectMapper.getSerializationConfig();
                            final BeanDescription beanDescription = serializationConfig
                                    .introspect(TypeFactory.defaultInstance().constructType(rawClass));
                            final JsonFormat.Value formatOverride = serializationConfig.getDefaultPropertyFormat(Map.Entry.class);
                            final JsonFormat.Value formatFromAnnotation = beanDescription.findExpectedFormat(null);
                            final JsonFormat.Value format = JsonFormat.Value.merge(formatFromAnnotation, formatOverride);
                            if (format.getShape() != JsonFormat.Shape.OBJECT) {
                                final Type mapType = Utils.replaceRawClassInType(javaType, Map.class);
                                return context.processType(mapType);
                            }
                        }
                    }
                    return null;
                }
            }
    );
}
 
Example 8
Source File: AnnotationIntrospectorPair.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public JsonFormat.Value findFormat(Annotated ann) {
    JsonFormat.Value v1 = _primary.findFormat(ann);
    JsonFormat.Value v2 = _secondary.findFormat(ann);
    if (v2 == null) { // shouldn't occur but just in case
        return v1;
    }
    return v2.withOverrides(v1);
}
 
Example 9
Source File: GuavaSerializers.java    From jackson-datatypes-collections with Apache License 2.0 5 votes vote down vote up
@Override
public JsonSerializer<?> findReferenceSerializer(SerializationConfig config, 
        ReferenceType refType, BeanDescription beanDesc, JsonFormat.Value formatOverrides,
        TypeSerializer contentTypeSerializer, JsonSerializer<Object> contentValueSerializer)
{
    final Class<?> raw = refType.getRawClass();
    if (Optional.class.isAssignableFrom(raw)) {
        boolean staticTyping = (contentTypeSerializer == null)
                && config.isEnabled(MapperFeature.USE_STATIC_TYPING);
        return new GuavaOptionalSerializer(refType, staticTyping,
                contentTypeSerializer, contentValueSerializer);
    }
    return null;
}
 
Example 10
Source File: BooleanSerializer.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public JsonSerializer<?> createContextual(SerializerProvider serializers,
        BeanProperty property) throws JsonMappingException
{
    JsonFormat.Value format = findFormatOverrides(serializers,
            property, Boolean.class);
    if (format != null) {
        JsonFormat.Shape shape = format.getShape();
        if (shape.isNumeric()) {
            return new AsNumber(_forPrimitive);
        }
    }
    return this;
}
 
Example 11
Source File: EnumSerializer.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Factory method used by {@link com.fasterxml.jackson.databind.ser.BasicSerializerFactory}
 * for constructing serializer instance of Enum types.
 * 
 * @since 2.1
 */
@SuppressWarnings("unchecked")
public static EnumSerializer construct(Class<?> enumClass, SerializationConfig config,
        BeanDescription beanDesc, JsonFormat.Value format)
{
    /* 08-Apr-2015, tatu: As per [databind#749], we cannot statically determine
     *   between name() and toString(), need to construct `EnumValues` with names,
     *   handle toString() case dynamically (for example)
     */
    EnumValues v = EnumValues.constructFromName(config, (Class<Enum<?>>) enumClass);
    Boolean serializeAsIndex = _isShapeWrittenUsingIndex(enumClass, format, true, null);
    return new EnumSerializer(v, serializeAsIndex);
}
 
Example 12
Source File: NumberSerializers.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public JsonSerializer<?> createContextual(SerializerProvider prov,
        BeanProperty property) throws JsonMappingException
{
    JsonFormat.Value format = findFormatOverrides(prov, property, handledType());
    if (format != null) {
        switch (format.getShape()) {
        case STRING:
            return ToStringSerializer.instance;
        default:
        }
    }
    return this;
}
 
Example 13
Source File: BasicSerializerFactory.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Helper method that handles configuration details when constructing serializers for
 * {@link java.util.Map} types.
 */
protected JsonSerializer<?> buildMapSerializer(SerializerProvider prov,
        MapType type, BeanDescription beanDesc,
        boolean staticTyping, JsonSerializer<Object> keySerializer,
        TypeSerializer elementTypeSerializer, JsonSerializer<Object> elementValueSerializer)
    throws JsonMappingException
{
    // [databind#467]: This is where we could allow serialization "as POJO": But! It's
    // nasty to undo, and does not apply on per-property basis. So, hardly optimal
    JsonFormat.Value format = beanDesc.findExpectedFormat(null);
    if ((format != null) && format.getShape() == JsonFormat.Shape.OBJECT) {
        return null;
    }

    JsonSerializer<?> ser = null;

    // Order of lookups:
    // 1. Custom serializers
    // 2. Annotations (@JsonValue, @JsonDeserialize)
    // 3. Defaults
    
    final SerializationConfig config = prov.getConfig();
    for (Serializers serializers : customSerializers()) { // (1) Custom
        ser = serializers.findMapSerializer(config, type, beanDesc,
                keySerializer, elementTypeSerializer, elementValueSerializer);
        if (ser != null) { break; }
    }
    if (ser == null) {
        ser = findSerializerByAnnotations(prov, type, beanDesc); // (2) Annotations
        if (ser == null) {
            Object filterId = findFilterId(config, beanDesc);
            // 01-May-2016, tatu: Which base type to use here gets tricky, since
            //   most often it ought to be `Map` or `EnumMap`, but due to abstract
            //   mapping it will more likely be concrete type like `HashMap`.
            //   So, for time being, just pass `Map.class`
            JsonIgnoreProperties.Value ignorals = config.getDefaultPropertyIgnorals(Map.class,
                    beanDesc.getClassInfo());
            Set<String> ignored = (ignorals == null) ? null
                    : ignorals.findIgnoredForSerialization();
            MapSerializer mapSer = MapSerializer.construct(ignored,
                    type, staticTyping, elementTypeSerializer,
                    keySerializer, elementValueSerializer, filterId);
            ser = _checkMapContentInclusion(prov, beanDesc, mapSer);
        }
    }
    // [databind#120]: Allow post-processing
    if (_factoryConfig.hasSerializerModifiers()) {
        for (BeanSerializerModifier mod : _factoryConfig.serializerModifiers()) {
            ser = mod.modifyMapSerializer(config, type, beanDesc, ser);
        }
    }
    return ser;
}
 
Example 14
Source File: BasicSerializerFactory.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * @since 2.9
 */
protected JsonSerializer<?> buildMapEntrySerializer(SerializerProvider prov,
        JavaType type, BeanDescription beanDesc, boolean staticTyping,
        JavaType keyType, JavaType valueType)
    throws JsonMappingException
{
    // [databind#865]: Allow serialization "as POJO" -- note: to undo, declare
    //   serialization as `Shape.NATURAL` instead; that's JSON Object too.
    JsonFormat.Value formatOverride = prov.getDefaultPropertyFormat(Map.Entry.class);
    JsonFormat.Value formatFromAnnotation = beanDesc.findExpectedFormat(null);
    JsonFormat.Value format = JsonFormat.Value.merge(formatFromAnnotation, formatOverride);
    if (format.getShape() == JsonFormat.Shape.OBJECT) {
        return null;
    }
    MapEntrySerializer ser = new MapEntrySerializer(valueType, keyType, valueType,
            staticTyping, createTypeSerializer(prov.getConfig(), valueType), null);

    final JavaType contentType = ser.getContentType();
    JsonInclude.Value inclV = _findInclusionWithContent(prov, beanDesc,
            contentType, Map.Entry.class);

    // Need to support global legacy setting, for now:
    JsonInclude.Include incl = (inclV == null) ? JsonInclude.Include.USE_DEFAULTS : inclV.getContentInclusion();
    if (incl == JsonInclude.Include.USE_DEFAULTS
            || incl == JsonInclude.Include.ALWAYS) {
        return ser;
    }

    // NOTE: mostly copied from `PropertyBuilder`; would be nice to refactor
    // but code is not identical nor are these types related
    Object valueToSuppress;
    boolean suppressNulls = true; // almost always, but possibly not with CUSTOM

    switch (incl) {
    case NON_DEFAULT:
        valueToSuppress = BeanUtil.getDefaultValue(contentType);
        if (valueToSuppress != null) {
            if (valueToSuppress.getClass().isArray()) {
                valueToSuppress = ArrayBuilders.getArrayComparator(valueToSuppress);
            }
        }
        break;
    case NON_ABSENT:
        valueToSuppress = contentType.isReferenceType()
                ? MapSerializer.MARKER_FOR_EMPTY : null;
        break;
    case NON_EMPTY:
        valueToSuppress = MapSerializer.MARKER_FOR_EMPTY;
        break;
    case CUSTOM:
        valueToSuppress = prov.includeFilterInstance(null, inclV.getContentFilter());
        if (valueToSuppress == null) { // is this legal?
            suppressNulls = true;
        } else {
            suppressNulls = prov.includeFilterSuppressNulls(valueToSuppress);
        }
        break;
    case NON_NULL:
    default: // should not matter but...
        valueToSuppress = null;
        break;
    }
    return ser.withContentInclusion(valueToSuppress, suppressNulls);
}
 
Example 15
Source File: DeserializationContext.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public final JsonFormat.Value getDefaultPropertyFormat(Class<?> baseType) {
    return _config.getDefaultPropertyFormat(baseType);
}
 
Example 16
Source File: ObjectArraySerializer.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public JsonSerializer<?> createContextual(SerializerProvider serializers,
        BeanProperty property)
    throws JsonMappingException
{
    TypeSerializer vts = _valueTypeSerializer;
    if (vts != null) {
        vts = vts.forProperty(property);
    }
    JsonSerializer<?> ser = null;
    Boolean unwrapSingle = null;

    // First: if we have a property, may have property-annotation overrides
    if (property != null) {
        AnnotatedMember m = property.getMember();
        final AnnotationIntrospector intr = serializers.getAnnotationIntrospector();
        if (m != null) {
            Object serDef = intr.findContentSerializer(m);
            if (serDef != null) {
                ser = serializers.serializerInstance(m, serDef);
            }
        }
    }
    JsonFormat.Value format = findFormatOverrides(serializers, property, handledType());
    if (format != null) {
        unwrapSingle = format.getFeature(JsonFormat.Feature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED);
    }
    if (ser == null) {
        ser = _elementSerializer;
    }
    // [databind#124]: May have a content converter
    ser = findContextualConvertingSerializer(serializers, property, ser);
    if (ser == null) {
        // 30-Sep-2012, tatu: One more thing -- if explicit content type is annotated,
        //   we can consider it a static case as well.
        if (_elementType != null) {
            if (_staticTyping && !_elementType.isJavaLangObject()) {
                ser = serializers.findValueSerializer(_elementType, property);
            }
        }
    }
    return withResolved(property, vts, ser, unwrapSingle);
}
 
Example 17
Source File: BasicSerializerFactory.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Method for checking if we can determine serializer to use based on set of
 * known primary types, checking for set of known base types (exact matches
 * having been compared against with <code>findSerializerByLookup</code>).
 * This does not include "secondary" interfaces, but
 * mostly concrete or abstract base classes.
 */
protected final JsonSerializer<?> findSerializerByPrimaryType(SerializerProvider prov, 
        JavaType type, BeanDescription beanDesc,
        boolean staticTyping)
    throws JsonMappingException
{
    Class<?> raw = type.getRawClass();
    
    // Then check for optional/external serializers 
    JsonSerializer<?> ser = findOptionalStdSerializer(prov, type, beanDesc, staticTyping);
    if (ser != null) {
        return ser;
    }
    
    if (Calendar.class.isAssignableFrom(raw)) {
        return CalendarSerializer.instance;
    }
    if (java.util.Date.class.isAssignableFrom(raw)) {
        return DateSerializer.instance;
    }
    if (Map.Entry.class.isAssignableFrom(raw)) {
        // 18-Oct-2015, tatu: With 2.7, need to dig type info:
        JavaType mapEntryType = type.findSuperType(Map.Entry.class);

        // 28-Apr-2015, tatu: TypeFactory does it all for us already so
        JavaType kt = mapEntryType.containedTypeOrUnknown(0);
        JavaType vt = mapEntryType.containedTypeOrUnknown(1);
        return buildMapEntrySerializer(prov, type, beanDesc, staticTyping, kt, vt);
    }
    if (ByteBuffer.class.isAssignableFrom(raw)) {
        return new ByteBufferSerializer();
    }
    if (InetAddress.class.isAssignableFrom(raw)) {
        return new InetAddressSerializer();
    }
    if (InetSocketAddress.class.isAssignableFrom(raw)) {
        return new InetSocketAddressSerializer();
    }
    if (TimeZone.class.isAssignableFrom(raw)) {
        return new TimeZoneSerializer();
    }
    if (java.nio.charset.Charset.class.isAssignableFrom(raw)) {
        return ToStringSerializer.instance;
    }
    if (Number.class.isAssignableFrom(raw)) {
        // 21-May-2014, tatu: Couple of alternatives actually
        JsonFormat.Value format = beanDesc.findExpectedFormat(null);
        if (format != null) {
            switch (format.getShape()) {
            case STRING:
                return ToStringSerializer.instance;
            case OBJECT: // need to bail out to let it be serialized as POJO
            case ARRAY: // or, I guess ARRAY; otherwise no point in speculating
                return null;
            default:
            }
        }
        return NumberSerializer.instance;
    }
    if (Enum.class.isAssignableFrom(raw)) {
        return buildEnumSerializer(prov.getConfig(), type, beanDesc);
    }
    return null;
}
 
Example 18
Source File: BasicSerializerFactory.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Helper method that handles configuration details when constructing serializers for
 * {@link java.util.List} types that support efficient by-index access
 * 
 * @since 2.1
 */
protected JsonSerializer<?> buildCollectionSerializer(SerializerProvider prov,
        CollectionType type, BeanDescription beanDesc, boolean staticTyping,
        TypeSerializer elementTypeSerializer, JsonSerializer<Object> elementValueSerializer) 
    throws JsonMappingException
{
    SerializationConfig config = prov.getConfig();
    JsonSerializer<?> ser = null;
    // Order of lookups:
    // 1. Custom serializers
    // 2. Annotations (@JsonValue, @JsonDeserialize)
    // 3. Defaults
    for (Serializers serializers : customSerializers()) { // (1) Custom
        ser = serializers.findCollectionSerializer(config,
                type, beanDesc, elementTypeSerializer, elementValueSerializer);
        if (ser != null) {
            break;
        }
    }

    if (ser == null) {
        ser = findSerializerByAnnotations(prov, type, beanDesc); // (2) Annotations
        if (ser == null) {
            // We may also want to use serialize Collections "as beans", if (and only if)
            // this is specified with `@JsonFormat(shape=Object)`
            JsonFormat.Value format = beanDesc.findExpectedFormat(null);
            if ((format != null) && format.getShape() == JsonFormat.Shape.OBJECT) {
                return null;
            }
            Class<?> raw = type.getRawClass();
            if (EnumSet.class.isAssignableFrom(raw)) {
                // this may or may not be available (Class doesn't; type of field/method does)
                JavaType enumType = type.getContentType();
                // and even if nominally there is something, only use if it really is enum
                if (!enumType.isEnumType()) {
                    enumType = null;
                }
                ser = buildEnumSetSerializer(enumType);
            } else {
                Class<?> elementRaw = type.getContentType().getRawClass();
                if (isIndexedList(raw)) {
                    if (elementRaw == String.class) {
                        // [JACKSON-829] Must NOT use if we have custom serializer
                        if (ClassUtil.isJacksonStdImpl(elementValueSerializer)) {
                            ser = IndexedStringListSerializer.instance;
                        }
                    } else {
                        ser = buildIndexedListSerializer(type.getContentType(), staticTyping,
                            elementTypeSerializer, elementValueSerializer);
                    }
                } else if (elementRaw == String.class) {
                    // [JACKSON-829] Must NOT use if we have custom serializer
                    if (ClassUtil.isJacksonStdImpl(elementValueSerializer)) {
                        ser = StringCollectionSerializer.instance;
                    }
                }
                if (ser == null) {
                    ser = buildCollectionSerializer(type.getContentType(), staticTyping,
                            elementTypeSerializer, elementValueSerializer);
                }
            }
        }
    }
    // [databind#120]: Allow post-processing
    if (_factoryConfig.hasSerializerModifiers()) {
        for (BeanSerializerModifier mod : _factoryConfig.serializerModifiers()) {
            ser = mod.modifyCollectionSerializer(config, type, beanDesc, ser);
        }
    }
    return ser;
}
 
Example 19
Source File: BeanDescription.java    From lams with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Method for checking what is the expected format for POJO, as
 * defined by defaults and possible annotations.
 * Note that this may be further refined by per-property annotations.
 * 
 * @since 2.1
 */
public abstract JsonFormat.Value findExpectedFormat(JsonFormat.Value defValue);
 
Example 20
Source File: BeanProperty.java    From lams with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Convenience method that is roughly equivalent to
 *<pre>
 *   return intr.findFormat(getMember());
 *</pre>
 * and specifically does NOT try to find per-type format defaults to merge;
 * use {@link #findPropertyFormat} if such defaults would be useful.
 *
 * @since 2.6
 * 
 * @deprecated since 2.8 use {@link #findPropertyFormat} instead.
 */
@Deprecated
public JsonFormat.Value findFormatOverrides(AnnotationIntrospector intr);