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

The following examples show how to use com.fasterxml.jackson.databind.jsontype.TypeSerializer. These examples are extracted from open source projects. 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 Project: vavr-jackson   Source File: LazySerializer.java    License: 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 2
/**
 * 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 3
/**
 * 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 4
Source Project: lams   Source File: BeanSerializerBase.java    License: 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 5
Source Project: lams   Source File: AsArraySerializerBase.java    License: 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 6
Source Project: lams   Source File: MapSerializer.java    License: 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 7
Source Project: beam   Source File: AwsModule.java    License: 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 Project: lams   Source File: ObjectArraySerializer.java    License: 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 9
@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 10
Source Project: lams   Source File: NumberSerializers.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public void serializeWithType(Object value, JsonGenerator gen,
        SerializerProvider provider, TypeSerializer typeSer)
        throws IOException {
    // no type info, just regular serialization
    serialize(value, gen, provider);
}
 
Example 11
Source Project: lams   Source File: ValueNode.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public void serializeWithType(JsonGenerator g, SerializerProvider provider,
        TypeSerializer typeSer)
    throws IOException
{
    WritableTypeId typeIdDef = typeSer.writeTypePrefix(g,
            typeSer.typeId(this, asToken()));
    serialize(g, provider);
    typeSer.writeTypeSuffix(g, typeIdDef);
}
 
Example 12
Source Project: lams   Source File: JSONWrappedObject.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public void serializeWithType(JsonGenerator jgen, SerializerProvider provider, TypeSerializer typeSer)
        throws IOException, JsonProcessingException
{
    // No type for JSONP wrapping: value serializer will handle typing for value:
    serialize(jgen, provider);
}
 
Example 13
@Deprecated // since 2.8
protected VirtualBeanPropertyWriter(BeanPropertyDefinition propDef,
        Annotations contextAnnotations, JavaType declaredType,
        JsonSerializer<?> ser, TypeSerializer typeSer, JavaType serType,
        JsonInclude.Value inclusion)
{
    this(propDef, contextAnnotations, declaredType, ser, typeSer, serType, inclusion, null);
}
 
Example 14
Source Project: healenium-web   Source File: NodeSerializer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void serializeWithType(Node value, JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
    WritableTypeId typeId = typeSer.typeId(value, Node.class, JsonToken.START_OBJECT);
    typeSer.writeTypePrefix(gen, typeId);
    serialize(value, gen, serializers);
    typeSer.writeTypeSuffix(gen, typeId);
}
 
Example 15
@Override
public TypeSerializer buildTypeSerializer(SerializationConfig config, JavaType baseType,
		Collection<NamedType> subtypes) {

	isAutowiredFiledInitialized = (this.capitalizer != null);
	return super.buildTypeSerializer(config, baseType, subtypes);
}
 
Example 16
Source Project: lams   Source File: Serializers.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public JsonSerializer<?> findCollectionSerializer(SerializationConfig config,
        CollectionType type, BeanDescription beanDesc,
        TypeSerializer elementTypeSerializer, JsonSerializer<Object> elementValueSerializer)
{
    return null;
}
 
Example 17
Source Project: lams   Source File: JSONPObject.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider provider, TypeSerializer typeSer)
        throws IOException
{
    // No type for JSONP wrapping: value serializer will handle typing for value:
    serialize(gen, provider);
}
 
Example 18
Source Project: cyclops   Source File: EvalSerializer.java    License: Apache License 2.0 5 votes vote down vote up
protected EvalSerializer(EvalSerializer base, BeanProperty property,
                         TypeSerializer vts, JsonSerializer<?> valueSer, NameTransformer unwrapper,
                         Object suppressableValue, boolean suppressNulls)
{
  super(base, property, vts, valueSer, unwrapper,
    suppressableValue, suppressNulls);
}
 
Example 19
Source Project: lams   Source File: UnknownSerializer.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public final void serializeWithType(Object value, JsonGenerator gen, SerializerProvider provider,
        TypeSerializer typeSer) throws IOException
{
    if (provider.isEnabled(SerializationFeature.FAIL_ON_EMPTY_BEANS)) {
        failForEmpty(provider, value);
    }
    WritableTypeId typeIdDef = typeSer.writeTypePrefix(gen,
            typeSer.typeId(value, JsonToken.START_OBJECT));
    typeSer.writeTypeSuffix(gen, typeIdDef);
}
 
Example 20
protected TableSerializer withResolved(final BeanProperty property,
        final TypeFactory typeFactory,
        final JsonSerializer<?> rowKeySer,
        final JsonSerializer<?> columnKeySer,
        final TypeSerializer vts,
        final JsonSerializer<?> valueSer )
{
    return new TableSerializer(this, property, typeFactory,
            rowKeySer, columnKeySer, vts, valueSer);
}
 
Example 21
@Override
public TypeSerializer buildTypeSerializer(SerializationConfig config, JavaType baseType, Collection<NamedType> subtypes) {
    //Copied this code from parent class, StdTypeResolverBuilder with same method name
    TypeIdResolver idRes = this.idResolver(config, baseType, subtypes, true, false);
    // have to escape "." in the middle of the "odata.type" otherwise it will be serialized to "odata": { "type":"Value"} JSON
    String escapedString = this._typeProperty.replace(".", "\\.");
    return new AsPropertyTypeSerializer(idRes, (BeanProperty) null, escapedString);
}
 
Example 22
@Override
public void serializeWithType(List<String> value, JsonGenerator g, SerializerProvider provider,
        TypeSerializer typeSer)
    throws IOException
{
    WritableTypeId typeIdDef = typeSer.writeTypePrefix(g,
            typeSer.typeId(value, JsonToken.START_ARRAY));
    serializeContents(value, g, provider, value.size());
    typeSer.writeTypeSuffix(g, typeIdDef);
}
 
Example 23
Source Project: lams   Source File: SerializerProvider.java    License: 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 Type for purpose of locating a serializer; usually dynamic
 *   runtime type, but can also be static declared type, depending on configuration
 * @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(Class<?> 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,
            _config.constructType(valueType));
    if (typeSer != null) {
        typeSer = typeSer.forProperty(property);
        ser = new TypeWrappedSerializer(typeSer, ser);
    }
    if (cache) {
        _serializerCache.addTypedSerializer(valueType, ser);
    }
    return ser;
}
 
Example 24
@Override
public void serializeWithType(T value, JsonGenerator gen, SerializerProvider ctxt, TypeSerializer typeSer)
        throws IOException {
    WritableTypeId typeIdDef = typeSer.writeTypePrefix(
            gen, ctxt, typeSer.typeId(value, JsonToken.START_OBJECT));
    serializeEntries(value, gen, ctxt);
    typeSer.writeTypeSuffix(gen, ctxt, typeIdDef);
}
 
Example 25
protected AtomicReferenceSerializer(AtomicReferenceSerializer base, BeanProperty property,
        TypeSerializer vts, JsonSerializer<?> valueSer,
        NameTransformer unwrapper,
        Object suppressableValue, boolean suppressNulls)
{
    super(base, property, vts, valueSer, unwrapper,
            suppressableValue, suppressNulls);
}
 
Example 26
@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 27
Source Project: lams   Source File: Serializers.java    License: 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 28
@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 Project: lams   Source File: MapSerializer.java    License: 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 30
Source Project: onetwo   Source File: UrlJsonSerializer.java    License: 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);
	}