Search in sources :

Example 16 with TypeSerializer

use of com.fasterxml.jackson.databind.jsontype.TypeSerializer in project jackson-databind by FasterXML.

the class SerializerProvider method findTypedValueSerializer.

/**
     * 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.
     * 
     * @param 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)
     * @param cache Whether resulting value serializer should be cached or not; this is just
     *    a hint 
     * @param 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.
     */
public JsonSerializer<Object> findTypedValueSerializer(JavaType valueType, boolean cache, BeanProperty property) throws JsonMappingException {
    // Two-phase lookups; local non-shared cache, then shared:
    JsonSerializer<Object> ser = _knownSerializers.typedValueSerializer(valueType);
    if (ser != null) {
        return ser;
    }
    // If not, maybe shared map already has it?
    ser = _serializerCache.typedValueSerializer(valueType);
    if (ser != null) {
        return ser;
    }
    // Well, let's just compose from pieces:
    ser = findValueSerializer(valueType, property);
    TypeSerializer typeSer = _serializerFactory.createTypeSerializer(_config, valueType);
    if (typeSer != null) {
        typeSer = typeSer.forProperty(property);
        ser = new TypeWrappedSerializer(typeSer, ser);
    }
    if (cache) {
        _serializerCache.addTypedSerializer(valueType, ser);
    }
    return ser;
}
Also used : TypeWrappedSerializer(com.fasterxml.jackson.databind.ser.impl.TypeWrappedSerializer) TypeSerializer(com.fasterxml.jackson.databind.jsontype.TypeSerializer)

Example 17 with TypeSerializer

use of com.fasterxml.jackson.databind.jsontype.TypeSerializer in project jackson-databind by FasterXML.

the class BeanSerializerFactory method findReferenceSerializer.

/**
     * @since 2.7
     */
public JsonSerializer<?> findReferenceSerializer(SerializerProvider prov, ReferenceType refType, BeanDescription beanDesc, boolean staticTyping) throws JsonMappingException {
    JavaType contentType = refType.getContentType();
    TypeSerializer contentTypeSerializer = contentType.getTypeHandler();
    final SerializationConfig config = prov.getConfig();
    if (contentTypeSerializer == null) {
        contentTypeSerializer = createTypeSerializer(config, contentType);
    }
    JsonSerializer<Object> contentSerializer = contentType.getValueHandler();
    for (Serializers serializers : customSerializers()) {
        JsonSerializer<?> ser = serializers.findReferenceSerializer(config, refType, beanDesc, contentTypeSerializer, contentSerializer);
        if (ser != null) {
            return ser;
        }
    }
    if (refType.isTypeOrSubTypeOf(AtomicReference.class)) {
        return buildAtomicReferenceSerializer(prov, refType, beanDesc, staticTyping, contentTypeSerializer, contentSerializer);
    }
    return null;
}
Also used : TypeSerializer(com.fasterxml.jackson.databind.jsontype.TypeSerializer)

Example 18 with TypeSerializer

use of com.fasterxml.jackson.databind.jsontype.TypeSerializer in project jackson-databind by FasterXML.

the class BeanSerializerFactory method constructBeanSerializer.

/*
    /**********************************************************
    /* Overridable non-public factory methods
    /**********************************************************
     */
/**
     * Method called to construct serializer for serializing specified bean type.
     * 
     * @since 2.1
     */
@SuppressWarnings("unchecked")
protected JsonSerializer<Object> constructBeanSerializer(SerializerProvider prov, BeanDescription beanDesc) throws JsonMappingException {
    // 05-Jul-2012, tatu: ... but we should be able to just return "unknown type" serializer, right?
    if (beanDesc.getBeanClass() == Object.class) {
        return prov.getUnknownTypeSerializer(Object.class);
    //            throw new IllegalArgumentException("Can not create bean serializer for Object.class");
    }
    final SerializationConfig config = prov.getConfig();
    BeanSerializerBuilder builder = constructBeanSerializerBuilder(beanDesc);
    builder.setConfig(config);
    // First: any detectable (auto-detect, annotations) properties to serialize?
    List<BeanPropertyWriter> props = findBeanProperties(prov, beanDesc, builder);
    if (props == null) {
        props = new ArrayList<BeanPropertyWriter>();
    } else {
        props = removeOverlappingTypeIds(prov, beanDesc, builder, props);
    }
    // [databind#638]: Allow injection of "virtual" properties:
    prov.getAnnotationIntrospector().findAndAddVirtualProperties(config, beanDesc.getClassInfo(), props);
    // [JACKSON-440] Need to allow modification bean properties to serialize:
    if (_factoryConfig.hasSerializerModifiers()) {
        for (BeanSerializerModifier mod : _factoryConfig.serializerModifiers()) {
            props = mod.changeProperties(config, beanDesc, props);
        }
    }
    // Any properties to suppress?
    props = filterBeanProperties(config, beanDesc, props);
    // Need to allow reordering of properties to serialize
    if (_factoryConfig.hasSerializerModifiers()) {
        for (BeanSerializerModifier mod : _factoryConfig.serializerModifiers()) {
            props = mod.orderProperties(config, beanDesc, props);
        }
    }
    /* And if Object Id is needed, some preparation for that as well: better
         * do before view handling, mostly for the custom id case which needs
         * access to a property
         */
    builder.setObjectIdWriter(constructObjectIdHandler(prov, beanDesc, props));
    builder.setProperties(props);
    builder.setFilterId(findFilterId(config, beanDesc));
    AnnotatedMember anyGetter = beanDesc.findAnyGetter();
    if (anyGetter != null) {
        JavaType type = anyGetter.getType();
        // copied from BasicSerializerFactory.buildMapSerializer():
        boolean staticTyping = config.isEnabled(MapperFeature.USE_STATIC_TYPING);
        JavaType valueType = type.getContentType();
        TypeSerializer typeSer = createTypeSerializer(config, valueType);
        // last 2 nulls; don't know key, value serializers (yet)
        // 23-Feb-2015, tatu: As per [databind#705], need to support custom serializers
        JsonSerializer<?> anySer = findSerializerFromAnnotation(prov, anyGetter);
        if (anySer == null) {
            // TODO: support '@JsonIgnoreProperties' with any setter?
            anySer = MapSerializer.construct(/* ignored props*/
            (Set<String>) null, type, staticTyping, typeSer, null, null, /*filterId*/
            null);
        }
        // TODO: can we find full PropertyName?
        PropertyName name = PropertyName.construct(anyGetter.getName());
        BeanProperty.Std anyProp = new BeanProperty.Std(name, valueType, null, anyGetter, PropertyMetadata.STD_OPTIONAL);
        builder.setAnyGetter(new AnyGetterWriter(anyProp, anyGetter, anySer));
    }
    // Next: need to gather view information, if any:
    processViews(config, builder);
    // Finally: let interested parties mess with the result bit more...
    if (_factoryConfig.hasSerializerModifiers()) {
        for (BeanSerializerModifier mod : _factoryConfig.serializerModifiers()) {
            builder = mod.updateBuilder(config, beanDesc, builder);
        }
    }
    JsonSerializer<Object> ser = (JsonSerializer<Object>) builder.build();
    if (ser == null) {
        // First: if there are known annotations, just create 'empty bean' serializer
        if (beanDesc.hasKnownClassAnnotations()) {
            return builder.createDummy();
        }
    }
    return ser;
}
Also used : TypeSerializer(com.fasterxml.jackson.databind.jsontype.TypeSerializer) FilteredBeanPropertyWriter(com.fasterxml.jackson.databind.ser.impl.FilteredBeanPropertyWriter)

Example 19 with TypeSerializer

use of com.fasterxml.jackson.databind.jsontype.TypeSerializer in project jackson-databind by FasterXML.

the class BeanSerializerBase method resolve.

/*
    /**********************************************************
    /* Post-constriction processing: resolvable, contextual
    /**********************************************************
     */
/**
     * We need to implement {@link ResolvableSerializer} to be able to
     * properly handle cyclic type references.
     */
@Override
public void resolve(SerializerProvider provider) throws JsonMappingException {
    int filteredCount = (_filteredProps == null) ? 0 : _filteredProps.length;
    for (int i = 0, len = _props.length; i < len; ++i) {
        BeanPropertyWriter prop = _props[i];
        // let's start with null serializer resolution actually
        if (!prop.willSuppressNulls() && !prop.hasNullSerializer()) {
            JsonSerializer<Object> nullSer = provider.findNullValueSerializer(prop);
            if (nullSer != null) {
                prop.assignNullSerializer(nullSer);
                // also: remember to replace filtered property too? (see [JACKSON-364])
                if (i < filteredCount) {
                    BeanPropertyWriter w2 = _filteredProps[i];
                    if (w2 != null) {
                        w2.assignNullSerializer(nullSer);
                    }
                }
            }
        }
        if (prop.hasSerializer()) {
            continue;
        }
        // [databind#124]: allow use of converters
        JsonSerializer<Object> ser = findConvertingSerializer(provider, prop);
        if (ser == null) {
            // Was the serialization type hard-coded? If so, use it
            JavaType type = prop.getSerializationType();
            // if not, we don't really know the actual type until we get the instance.
            if (type == null) {
                type = prop.getType();
                if (!type.isFinal()) {
                    if (type.isContainerType() || type.containedTypeCount() > 0) {
                        prop.setNonTrivialBaseType(type);
                    }
                    continue;
                }
            }
            ser = provider.findValueSerializer(type, prop);
            /* 04-Feb-2010, tatu: We may have stashed type serializer for content types
                 *   too, earlier; if so, it's time to connect the dots here:
                 */
            if (type.isContainerType()) {
                TypeSerializer typeSer = type.getContentType().getTypeHandler();
                if (typeSer != null) {
                    // for now, can do this only for standard containers...
                    if (ser instanceof ContainerSerializer<?>) {
                        // ugly casts... but necessary
                        @SuppressWarnings("unchecked") JsonSerializer<Object> ser2 = (JsonSerializer<Object>) ((ContainerSerializer<?>) ser).withValueTypeSerializer(typeSer);
                        ser = ser2;
                    }
                }
            }
        }
        // and maybe replace filtered property too?
        if (i < filteredCount) {
            BeanPropertyWriter w2 = _filteredProps[i];
            if (w2 != null) {
                w2.assignSerializer(ser);
                //    may require work to be done, which does lead to an actual issue.
                continue;
            }
        }
        prop.assignSerializer(ser);
    }
    // also, any-getter may need to be resolved
    if (_anyGetterWriter != null) {
        // 23-Feb-2015, tatu: Misleading, as this actually triggers call to contextualization...
        _anyGetterWriter.resolve(provider);
    }
}
Also used : TypeSerializer(com.fasterxml.jackson.databind.jsontype.TypeSerializer)

Example 20 with TypeSerializer

use of com.fasterxml.jackson.databind.jsontype.TypeSerializer in project jackson-databind by FasterXML.

the class IndexedListSerializer method serializeContentsUsing.

public void serializeContentsUsing(List<?> value, JsonGenerator jgen, SerializerProvider provider, JsonSerializer<Object> ser) throws IOException {
    final int len = value.size();
    if (len == 0) {
        return;
    }
    final TypeSerializer typeSer = _valueTypeSerializer;
    for (int i = 0; i < len; ++i) {
        Object elem = value.get(i);
        try {
            if (elem == null) {
                provider.defaultSerializeNull(jgen);
            } else if (typeSer == null) {
                ser.serialize(elem, jgen, provider);
            } else {
                ser.serializeWithType(elem, jgen, provider, typeSer);
            }
        } catch (Exception e) {
            // [JACKSON-55] Need to add reference information
            wrapAndThrow(provider, e, value, i);
        }
    }
}
Also used : TypeSerializer(com.fasterxml.jackson.databind.jsontype.TypeSerializer) IOException(java.io.IOException)

Aggregations

TypeSerializer (com.fasterxml.jackson.databind.jsontype.TypeSerializer)24 IOException (java.io.IOException)8 PropertySerializerMap (com.fasterxml.jackson.databind.ser.impl.PropertySerializerMap)3 JsonFormat (com.fasterxml.jackson.annotation.JsonFormat)2 AnnotatedMember (com.fasterxml.jackson.databind.introspect.AnnotatedMember)2 NamedType (com.fasterxml.jackson.databind.jsontype.NamedType)2 FilteredBeanPropertyWriter (com.fasterxml.jackson.databind.ser.impl.FilteredBeanPropertyWriter)2 TypeWrappedSerializer (com.fasterxml.jackson.databind.ser.impl.TypeWrappedSerializer)2 JsonInclude (com.fasterxml.jackson.annotation.JsonInclude)1