com.fasterxml.jackson.databind.jsontype.TypeSerializer Java Examples

The following examples show how to use com.fasterxml.jackson.databind.jsontype.TypeSerializer. 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: BeanSerializerFactory.java    From bistoury with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Method called to create a type information serializer for values of given
 * container property
 * if one is needed. If not needed (no polymorphic handling configured), should
 * return null.
 *
 * @param containerType Declared type of the container to use as the base type for type information serializer
 *
 * @return Type serializer to use for property value contents, if one is needed; null if not.
 */
public TypeSerializer findPropertyContentTypeSerializer(JavaType containerType,
                                                        SerializationConfig config, AnnotatedMember accessor)
        throws JsonMappingException
{
    JavaType contentType = containerType.getContentType();
    AnnotationIntrospector ai = config.getAnnotationIntrospector();
    TypeResolverBuilder<?> b = ai.findPropertyContentTypeResolver(config, accessor, containerType);
    TypeSerializer typeSer;

    // Defaulting: if no annotations on member, check value class
    if (b == null) {
        typeSer = createTypeSerializer(config, contentType);
    } else {
        Collection<NamedType> subtypes = config.getSubtypeResolver().collectAndResolveSubtypesByClass(config,
                accessor, contentType);
        typeSer = b.buildTypeSerializer(config, contentType, subtypes);
    }
    return typeSer;
}
 
Example #2
Source File: BeanSerializerFactory.java    From bistoury with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Helper method called to ensure that we do not have "duplicate" type ids.
 * Added to resolve [databind#222]
 *
 * @since 2.6
 */
protected List<BeanPropertyWriter> removeOverlappingTypeIds(SerializerProvider prov,
                                                            BeanDescription beanDesc, BeanSerializerBuilder builder,
                                                            List<BeanPropertyWriter> props)
{
    for (int i = 0, end = props.size(); i < end; ++i) {
        BeanPropertyWriter bpw = props.get(i);
        TypeSerializer td = bpw.getTypeSerializer();
        if ((td == null) || (td.getTypeInclusion() != As.EXTERNAL_PROPERTY)) {
            continue;
        }
        String n = td.getPropertyName();
        PropertyName typePropName = PropertyName.construct(n);

        for (BeanPropertyWriter w2 : props) {
            if ((w2 != bpw) && w2.wouldConflictWithName(typePropName)) {
                bpw.assignTypeSerializer(null);
                break;
            }
        }
    }
    return props;
}
 
Example #3
Source File: LazySerializer.java    From vavr-jackson with Apache License 2.0 6 votes vote down vote up
@Override
public JsonSerializer<?> createContextual(SerializerProvider provider, BeanProperty property) throws JsonMappingException {
    TypeSerializer vts = valueTypeSerializer;
    if (vts != null) {
        vts = vts.forProperty(property);
    }
    JsonSerializer<?> ser = valueSerializer;
    if (ser == null) {
        // A few conditions needed to be able to fetch serializer here:
        if (useStatic(provider, property, valueType)) {
            ser = provider.findTypedValueSerializer(valueType, true, property);
        }
    } else {
        ser = provider.handlePrimaryContextualization(ser, property);
    }
    return new LazySerializer(fullType, valueType, vts, ser);
}
 
Example #4
Source File: AsArraySerializerBase.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * @deprecated Since 2.6 Use variants that either take 'src', or do NOT pass
 *    BeanProperty
 */
@Deprecated
protected AsArraySerializerBase(Class<?> cls, JavaType et, boolean staticTyping,
        TypeSerializer vts, BeanProperty property, JsonSerializer<Object> elementSerializer)
{
    // typing with generics is messy... have to resort to this:
    super(cls, false);
    _elementType = et;
    // static if explicitly requested, or if element type is final
    _staticTyping = staticTyping || (et != null && et.isFinal());
    _valueTypeSerializer = vts;
    _property = property;
    _elementSerializer = elementSerializer;
    _dynamicSerializers = PropertySerializerMap.emptyForProperties();
    _unwrapSingle = null;
}
 
Example #5
Source File: ObjectArraySerializer.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public void serializeTypedContents(Object[] value, JsonGenerator jgen, SerializerProvider provider) throws IOException
{
    final int len = value.length;
    final TypeSerializer typeSer = _valueTypeSerializer;
    int i = 0;
    Object elem = null;
    try {
        PropertySerializerMap serializers = _dynamicSerializers;
        for (; i < len; ++i) {
            elem = value[i];
            if (elem == null) {
                provider.defaultSerializeNull(jgen);
                continue;
            }
            Class<?> cc = elem.getClass();
            JsonSerializer<Object> serializer = serializers.serializerFor(cc);
            if (serializer == null) {
                serializer = _findAndAddDynamic(serializers, cc, provider);
            }
            serializer.serializeWithType(elem, jgen, provider, typeSer);
        }
    } catch (Exception e) {
        wrapAndThrow(provider, e, elem, i);
    }
}
 
Example #6
Source File: MultimapSerializer.java    From jackson-datatypes-collections with Apache License 2.0 6 votes vote down vote up
@Override
    public void serializeWithType(Multimap<?,?> value, JsonGenerator gen,
            SerializerProvider ctxt, TypeSerializer typeSer)
        throws IOException
    {
        gen.setCurrentValue(value);
        WritableTypeId typeIdDef = typeSer.writeTypePrefix(gen, ctxt,
                typeSer.typeId(value, JsonToken.START_OBJECT));
        if (!value.isEmpty()) {
// 20-Mar-2017, tatu: And this is where [datatypes-collections#7] would be
//     plugged in...
//            if (_sortKeys || provider.isEnabled(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS)) {
//              value = _orderEntries(value, gen, provider);
//          }
            if (_filterId != null) {
                serializeFilteredFields(value, gen, ctxt);
            } else {
                serializeFields(value, gen, ctxt);
            }
        }
        typeSer.writeTypeSuffix(gen, ctxt, typeIdDef);
    }
 
Example #7
Source File: AwsModule.java    From beam with Apache License 2.0 6 votes vote down vote up
@Override
public void serializeWithType(
    AwsCredentialsProvider credentialsProvider,
    JsonGenerator jsonGenerator,
    SerializerProvider serializer,
    TypeSerializer typeSerializer)
    throws IOException {
  WritableTypeId typeId =
      typeSerializer.writeTypePrefix(
          jsonGenerator, typeSerializer.typeId(credentialsProvider, JsonToken.START_OBJECT));
  if (credentialsProvider.getClass().equals(StaticCredentialsProvider.class)) {
    jsonGenerator.writeStringField(
        ACCESS_KEY_ID, credentialsProvider.resolveCredentials().accessKeyId());
    jsonGenerator.writeStringField(
        SECRET_ACCESS_KEY, credentialsProvider.resolveCredentials().secretAccessKey());
  } else if (!SINGLETON_CREDENTIAL_PROVIDERS.contains(credentialsProvider.getClass())) {
    throw new IllegalArgumentException(
        "Unsupported AWS credentials provider type " + credentialsProvider.getClass());
  }
  typeSerializer.writeTypeSuffix(jsonGenerator, typeId);
}
 
Example #8
Source File: MapSerializer.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void serializeWithType(Map<?,?> value, JsonGenerator gen, SerializerProvider provider,
        TypeSerializer typeSer)
    throws IOException
{
    // [databind#631]: Assign current value, to be accessible by custom serializers
    gen.setCurrentValue(value);
    WritableTypeId typeIdDef = typeSer.writeTypePrefix(gen,
            typeSer.typeId(value, JsonToken.START_OBJECT));
    if (!value.isEmpty()) {
        if (_sortKeys || provider.isEnabled(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS)) {
            value = _orderEntries(value, gen, provider);
        }
        PropertyFilter pf;
        if ((_filterId != null) && (pf = findPropertyFilter(provider, _filterId, value)) != null) {
            serializeFilteredFields(value, gen, provider, pf, _suppressableValue);
        } else if ((_suppressableValue != null) || _suppressNulls) {
            serializeOptionalFields(value, gen, provider, _suppressableValue);
        } else if (_valueSerializer != null) {
            serializeFieldsUsing(value, gen, provider, _valueSerializer);
        } else {
            serializeFields(value, gen, provider);
        }
    }
    typeSer.writeTypeSuffix(gen, typeIdDef);
}
 
Example #9
Source File: BeanSerializerBase.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
protected  void _serializeObjectId(Object bean, JsonGenerator g,
        SerializerProvider provider,
        TypeSerializer typeSer, WritableObjectId objectId) throws IOException
{
    final ObjectIdWriter w = _objectIdWriter;
    WritableTypeId typeIdDef = _typeIdDef(typeSer, bean, JsonToken.START_OBJECT);

    typeSer.writeTypePrefix(g, typeIdDef);
    objectId.writeAsField(g, provider, w);
    if (_propertyFilterId != null) {
        serializeFieldsFiltered(bean, g, provider);
    } else {
        serializeFields(bean, g, provider);
    }
    typeSer.writeTypeSuffix(g, typeIdDef);
}
 
Example #10
Source File: SerializerProvider.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #11
Source File: MultimapSerializer.java    From jackson-datatypes-collections with Apache License 2.0 5 votes vote down vote up
public MultimapSerializer(MapLikeType type, BeanDescription beanDesc,
        JsonSerializer<Object> keySerializer, TypeSerializer vts,
        JsonSerializer<Object> valueSerializer,
        Set<String> ignoredEntries, Object filterId)
{
    super(type, null);
    _type = type;
    _keySerializer = keySerializer;
    _valueTypeSerializer = vts;
    _valueSerializer = valueSerializer;
    _ignoredEntries = ignoredEntries;
    _filterId = filterId;
    _sortKeys = false;
}
 
Example #12
Source File: RefRefMapIterableSerializer.java    From jackson-datatypes-collections with Apache License 2.0 5 votes vote down vote up
public RefRefMapIterableSerializer(
        JavaType type,
        JsonSerializer<Object> keySerializer, TypeSerializer vts, JsonSerializer<Object> valueSerializer,
        Set<String> ignoredEntries
) {
    super(type, MapIterable.class, keySerializer, vts, valueSerializer, ignoredEntries);
}
 
Example #13
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 #14
Source File: MapEntrySerializer.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void serializeWithType(Map.Entry<?, ?> value, JsonGenerator g,
        SerializerProvider provider, TypeSerializer typeSer) throws IOException
{
    // [databind#631]: Assign current value, to be accessible by custom serializers
    g.setCurrentValue(value);
    WritableTypeId typeIdDef = typeSer.writeTypePrefix(g,
            typeSer.typeId(value, JsonToken.START_OBJECT));
    serializeDynamic(value, g, provider);
    typeSer.writeTypeSuffix(g, typeIdDef);
}
 
Example #15
Source File: Serializers.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public JsonSerializer<?> findCollectionLikeSerializer(SerializationConfig config,
        CollectionLikeType type, BeanDescription beanDesc,
        TypeSerializer elementTypeSerializer, JsonSerializer<Object> elementValueSerializer)
{
    return null;
}
 
Example #16
Source File: VavrSerializers.java    From vavr-jackson with Apache License 2.0 5 votes vote down vote up
@Override
public JsonSerializer<?> findReferenceSerializer(SerializationConfig config,
                                                 ReferenceType type, BeanDescription beanDesc,
                                                 TypeSerializer contentTypeSerializer, JsonSerializer<Object> contentValueSerializer) {
    Class<?> raw = type.getRawClass();
    if (Lazy.class.isAssignableFrom(raw)) {
        return new LazySerializer(type, type.getContentType(), contentTypeSerializer, contentValueSerializer);
    }
    if (Option.class.isAssignableFrom(raw)) {
        return new OptionSerializer(type, type.getContentType(), contentTypeSerializer, contentValueSerializer, settings.useOptionInPlainFormat());
    }
    return super.findReferenceSerializer(config, type, beanDesc, contentTypeSerializer, contentValueSerializer);
}
 
Example #17
Source File: Serializers.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public JsonSerializer<?> findArraySerializer(SerializationConfig config,
        ArrayType type, BeanDescription beanDesc,
        TypeSerializer elementTypeSerializer, JsonSerializer<Object> elementValueSerializer)
{
    return null;
}
 
Example #18
Source File: AsArraySerializerBase.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void serializeWithType(T value, JsonGenerator g, SerializerProvider provider,
        TypeSerializer typeSer) throws IOException
{
    // [databind#631]: Assign current value, to be accessible by custom serializers
    g.setCurrentValue(value);
    WritableTypeId typeIdDef = typeSer.writeTypePrefix(g,
            typeSer.typeId(value, JsonToken.START_ARRAY));
    serializeContents(value, g, provider);
    typeSer.writeTypeSuffix(g, typeIdDef);
}
 
Example #19
Source File: GuavaOptionalSerializer.java    From jackson-datatypes-collections with Apache License 2.0 5 votes vote down vote up
public GuavaOptionalSerializer(GuavaOptionalSerializer base, BeanProperty property,
        TypeSerializer vts, JsonSerializer<?> valueSer, NameTransformer unwrapper,
        Object suppressableValue, boolean suppressNulls)
{
    super(base, property, vts, valueSer, unwrapper,
            suppressableValue, suppressNulls);
}
 
Example #20
Source File: RefRefMapSerializer.java    From jackson-datatypes-collections with Apache License 2.0 5 votes vote down vote up
@Override
public void serializeWithType(
        T value, JsonGenerator gen,
        SerializerProvider ctxt, TypeSerializer typeSer
) throws IOException {
    gen.setCurrentValue(value);
    WritableTypeId typeIdDef = typeSer.writeTypePrefix(gen, ctxt,
            typeSer.typeId(value, JsonToken.START_OBJECT));
    if (!isEmpty(ctxt, value)) {
        serializeFields(value, gen, ctxt);
    }
    typeSer.writeTypeSuffix(gen, ctxt, typeIdDef);
}
 
Example #21
Source File: InetSocketAddressSerializer.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void serializeWithType(InetSocketAddress value, JsonGenerator g,
        SerializerProvider provider, TypeSerializer typeSer) throws IOException
{
    // Better ensure we don't use specific sub-classes...
    WritableTypeId typeIdDef = typeSer.writeTypePrefix(g,
            typeSer.typeId(value, InetSocketAddress.class, JsonToken.VALUE_STRING));
    serialize(value, g, provider);
    typeSer.writeTypeSuffix(g, typeIdDef);
}
 
Example #22
Source File: MissingNode.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void serializeWithType(JsonGenerator g, SerializerProvider provider,
        TypeSerializer typeSer)
    throws IOException, JsonProcessingException
{
    g.writeNull();
}
 
Example #23
Source File: Serializers.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public JsonSerializer<?> findReferenceSerializer(SerializationConfig config,
        ReferenceType type, BeanDescription beanDesc,
        TypeSerializer contentTypeSerializer, JsonSerializer<Object> contentValueSerializer) {
    // 21-Oct-2015, tatu: For backwards compatibility, let's delegate to "bean" variant,
    //    for 2.7 -- remove work-around from 2.8 or later
    return findSerializer(config, type, beanDesc);
}
 
Example #24
Source File: ObjectArraySerializer.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public ObjectArraySerializer(ObjectArraySerializer src, TypeSerializer vts)
{
    super(src);
    _elementType = src._elementType;
    _valueTypeSerializer = vts;
    _staticTyping = src._staticTyping;
    _dynamicSerializers = src._dynamicSerializers;
    _elementSerializer = src._elementSerializer;
}
 
Example #25
Source File: SimpleSerializers.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public JsonSerializer<?> findMapLikeSerializer(SerializationConfig config,
        MapLikeType type, BeanDescription beanDesc,
        JsonSerializer<Object> keySerializer,
        TypeSerializer elementTypeSerializer, JsonSerializer<Object> elementValueSerializer) {
    return findSerializer(config, type, beanDesc);
}
 
Example #26
Source File: UrlJsonSerializer.java    From onetwo with Apache License 2.0 5 votes vote down vote up
/****
	 * 序列化需要类型形式时,即objectMapper.enableDefaultTyping(DefaultTyping.NON_FINAL, As.PROPERTY),必须实现此方法
	 */
	@Override
	public void serializeWithType(Object value, JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
		typeSer.writeTypePrefixForScalar(value, gen);
		serialize(value, gen, serializers);
//		typeSer.writeTypePrefixForScalar(value, gen);
		typeSer.writeTypeSuffixForScalar(value, gen);
	}
 
Example #27
Source File: MapSerializer.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * @since 2.5
 * @deprecated // since 2.9
 */
@Deprecated // since 2.9
protected MapSerializer(MapSerializer src, TypeSerializer vts,
        Object suppressableValue)
{
    this(src, vts, suppressableValue, false);
}
 
Example #28
Source File: NonTypedScalarSerializerBase.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public final void serializeWithType(T value, JsonGenerator gen, SerializerProvider provider,
        TypeSerializer typeSer) throws IOException
{
    // no type info, just regular serialization
    serialize(value, gen, provider);            
}
 
Example #29
Source File: OffsetTimeSerializer.java    From jackson-modules-java8 with Apache License 2.0 5 votes vote down vote up
@Override
public void serializeWithType(OffsetTime value, JsonGenerator g, SerializerProvider ctxt,
        TypeSerializer typeSer) throws IOException
{
    WritableTypeId typeIdDef = typeSer.writeTypePrefix(g, ctxt,
            typeSer.typeId(value, serializationShape(ctxt)));
    // need to write out to avoid double-writing array markers
    if (typeIdDef.valueShape == JsonToken.START_ARRAY) {
        _serializeAsArrayContents(value, g, ctxt);
    } else {
        String str = (_formatter == null) ? value.toString() : value.format(_formatter);
        g.writeString(str);
    }
    typeSer.writeTypeSuffix(g, ctxt, typeIdDef);
}
 
Example #30
Source File: AtomicReferenceSerializer.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected AtomicReferenceSerializer(AtomicReferenceSerializer base, BeanProperty property,
        TypeSerializer vts, JsonSerializer<?> valueSer,
        NameTransformer unwrapper,
        Object suppressableValue, boolean suppressNulls)
{
    super(base, property, vts, valueSer, unwrapper,
            suppressableValue, suppressNulls);
}