Java Code Examples for com.fasterxml.jackson.databind.JsonSerializer#serialize()

The following examples show how to use com.fasterxml.jackson.databind.JsonSerializer#serialize() . 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: JoynrListSerializer.java    From joynr with Apache License 2.0 6 votes vote down vote up
@Override
public void serialize(List<?> value, JsonGenerator jgen, SerializerProvider provider) throws IOException,
                                                                                      JsonGenerationException {

    jgen.writeStartArray();
    for (Object elem : value) {
        if (elem == null) {
            provider.defaultSerializeNull(jgen);
        } else {
            Class<?> clazz = elem.getClass();
            JsonSerializer<Object> serializer = serializers.get(clazz);
            if (serializer == null) {
                serializer = provider.findTypedValueSerializer(clazz, false, null);
            }
            serializer.serialize(elem, jgen, provider);
        }
    }
    jgen.writeEndArray();

}
 
Example 2
Source File: ValueSerializer.java    From vavr-jackson with Apache License 2.0 6 votes vote down vote up
@Override
public void serialize(T value, JsonGenerator gen, SerializerProvider provider) throws IOException {
    Object obj = toJavaObj(value);
    if (obj == null) {
        provider.getDefaultNullValueSerializer().serialize(null, gen, provider);
    } else {
        JsonSerializer<Object> ser;
        try {
            JavaType emulated = emulatedJavaType(provider.getTypeFactory());
            if (emulated.getRawClass() != Object.class) {
                ser = provider.findTypedValueSerializer(emulated, true, beanProperty);
            } else {
                ser = provider.findTypedValueSerializer(obj.getClass(), true, beanProperty);
            }
        } catch (Exception ignore) {
            ser = provider.findTypedValueSerializer(obj.getClass(), true, beanProperty);
        }
        ser.serialize(obj, gen, provider);
    }
}
 
Example 3
Source File: JoynrArraySerializer.java    From joynr with Apache License 2.0 6 votes vote down vote up
@Override
public void serialize(Object[] value, JsonGenerator gen, SerializerProvider provider) throws IOException {
    gen.writeStartArray();
    for (Object elem : value) {
        if (elem == null) {
            provider.defaultSerializeNull(gen);
        } else {
            Class<?> clazz = elem.getClass();
            JsonSerializer<Object> serializer = serializers.get(clazz);
            if (serializer == null) {
                serializer = provider.findTypedValueSerializer(clazz, false, null);
            }
            serializer.serialize(elem, gen, provider);
        }
    }
    gen.writeEndArray();

}
 
Example 4
Source File: MapSerializerManager.java    From caravan with Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
  Map<?, ?> map = (Map<?, ?>) o;

  if (!map.isEmpty()) {
    ClassPair classPair = inspectKeyValueClass(map);

    if (classPair.keyClass == null) {
      throw new RuntimeException("Can not serialize map whose keys are all null");
    }

    if (classPair.valueClass == null) {
      throw new RuntimeException("Can not serialize map whose values are all null");
    }

    JsonSerializer serializer = serializers.get(classPair);

    if (serializer == null) {
      serializer = factory.createSerializer(classPair);
      serializers.put(classPair, serializer);
    }

    serializer.serialize(o, jsonGenerator, serializerProvider);
  }
}
 
Example 5
Source File: BlockHeaderExtensionsSerializer.java    From steem-java-api-wrapper with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void serialize(BlockHeaderExtensions blockHeaderExtensions, JsonGenerator jsonGenerator,
        SerializerProvider serializerProvider) throws IOException {
    JavaType javaType = serializerProvider.constructType(CommentPayoutBeneficiaries.class);
    BeanDescription beanDesc = serializerProvider.getConfig().introspect(javaType);
    JsonSerializer<Object> serializer = BeanSerializerFactory.instance.findBeanSerializer(serializerProvider,
            javaType, beanDesc);

    jsonGenerator.writeStartArray();

    if (blockHeaderExtensions instanceof Version) {
        jsonGenerator.writeNumber(BlockHeaderExtentsionsType.VERSION.ordinal());
        serializer.serialize((Version) blockHeaderExtensions, jsonGenerator, serializerProvider);
    } else if (blockHeaderExtensions instanceof HardforkVersionVote) {
        jsonGenerator.writeNumber(BlockHeaderExtentsionsType.HARDFORK_VERSION_VOTE.ordinal());
        serializer.serialize((HardforkVersionVote) blockHeaderExtensions, jsonGenerator, serializerProvider);
    } else {
        throw new IllegalArgumentException(
                "Unknown extension type class '" + blockHeaderExtensions.getClass().getSimpleName() + "'.");
    }

    jsonGenerator.writeEndArray();
}
 
Example 6
Source File: Tuple1Serializer.java    From cyclops with Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(Tuple1<?> value, JsonGenerator gen, SerializerProvider serializers) throws IOException {


    Object[] array = new Object[]{value._1()};
    gen.writeStartArray();
    for(Object o : array) {
      JsonSerializer<Object> ser = serializers.findTypedValueSerializer(o.getClass(),true,null);
      ser.serialize(o, gen, serializers);
    }
    gen.writeEndArray();


}
 
Example 7
Source File: SdkPojoSerializer.java    From cloudformation-cli-java-plugin with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private void writeObject(Object value, SdkField<?> sdkField, JsonGenerator gen, SerializerProvider serializers)
    throws IOException {
    MarshallingType<?> type = sdkField.marshallingType();
    if (type.equals(MarshallingType.BOOLEAN)) {
        gen.writeBoolean((Boolean) value);
    } else if (type.equals(MarshallingType.DOUBLE)) {
        gen.writeNumber((Double) value);
    } else if (type.equals(MarshallingType.INTEGER)) {
        gen.writeNumber((Integer) value);
    } else if (type.equals(MarshallingType.FLOAT)) {
        gen.writeNumber((Float) value);
    } else if (type.equals(MarshallingType.STRING)) {
        gen.writeString((String) value);
    } else if (type.equals(MarshallingType.BIG_DECIMAL)) {
        gen.writeNumber((BigDecimal) value);
    } else if (type.equals(MarshallingType.SDK_BYTES)) {
        gen.writeBinary(((SdkBytes) value).asByteArray());
    } else if (type.equals(MarshallingType.INSTANT)) {
        JsonSerializer<Object> serializer = serializers.findValueSerializer(Instant.class);
        serializer.serialize(value, gen, serializers);
    } else if (type.equals(MarshallingType.LONG)) {
        gen.writeNumber((Long) value);
    } else if (type.equals(MarshallingType.SDK_POJO)) {
        writeSdkPojo((SdkPojo) value, gen, serializers);
    } else if (type.equals(MarshallingType.LIST)) {
        writeSdkList((Collection<Object>) value, sdkField, gen, serializers);
    } else if (type.equals(MarshallingType.MAP)) {
        writeSdkMap((Map<String, Object>) value, sdkField, gen, serializers);
    }
}
 
Example 8
Source File: Tuple5Serializer.java    From cyclops with Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(Tuple5<?,?,?,?,?> value, JsonGenerator gen, SerializerProvider serializers) throws IOException {

  Object[] array = new Object[]{value._1(),value._2(),value._3(),value._4(),value._5()};
  gen.writeStartArray();
  for(Object o : array) {
    JsonSerializer<Object> ser = serializers.findTypedValueSerializer(o.getClass(),true,null);
    ser.serialize(o, gen, serializers);
  }
  gen.writeEndArray();
}
 
Example 9
Source File: ResourcesMapper.java    From mobilecloud-15 with Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(Resources value, JsonGenerator jgen,
		SerializerProvider provider) throws IOException,
		JsonProcessingException {
	// Extracted the actual data inside of the Resources object
	// that we care about (e.g., the list of Video objects)
	Object content = value.getContent();
	// Instead of all of the Resources member variables, etc.
	// Just mashall the actual content (Videos) into the JSON
	JsonSerializer<Object> s = provider.findValueSerializer(
			content.getClass(), null);
	s.serialize(content, jgen, provider);
}
 
Example 10
Source File: ResourcesMapper.java    From mobilecloud-15 with Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(Resources value, JsonGenerator jgen,
		SerializerProvider provider) throws IOException,
		JsonProcessingException {
	// Extracted the actual data inside of the Resources object
	// that we care about (e.g., the list of Video objects)
	Object content = value.getContent();
	// Instead of all of the Resources member variables, etc.
	// Just mashall the actual content (Videos) into the JSON
	JsonSerializer<Object> s = provider.findValueSerializer(
			content.getClass(), null);
	s.serialize(content, jgen, provider);
}
 
Example 11
Source File: Tuple3Serializer.java    From cyclops with Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(Tuple3<?,?,?> value, JsonGenerator gen, SerializerProvider serializers) throws IOException {

  Object[] array = new Object[]{value._1(),value._2(),value._3()};
  gen.writeStartArray();
  for(Object o : array) {
    JsonSerializer<Object> ser = serializers.findTypedValueSerializer(o.getClass(),true,null);
    ser.serialize(o, gen, serializers);
  }
  gen.writeEndArray();

}
 
Example 12
Source File: ResourcesMapper.java    From mobilecloud-15 with Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(Resources value, JsonGenerator jgen,
		SerializerProvider provider) throws IOException,
		JsonProcessingException {
	// Extracted the actual data inside of the Resources object
	// that we care about (e.g., the list of Video objects)
	Object content = value.getContent();
	// Instead of all of the Resources member variables, etc.
	// Just mashall the actual content (Videos) into the JSON
	JsonSerializer<Object> s = provider.findValueSerializer(
			content.getClass(), null);
	s.serialize(content, jgen, provider);
}
 
Example 13
Source File: CustomSimpleSerializers.java    From caravan with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("rawtypes")
@Override
public JsonSerializer<?> findArraySerializer(SerializationConfig config, ArrayType type, BeanDescription beanDesc, TypeSerializer elementTypeSerializer,
    JsonSerializer<Object> elementValueSerializer) {

  Class<?> contentClass = type.getContentType().getRawClass();
  TypeCustomizationFactory factory = provider.factoryForArrayOf(contentClass);

  if (factory != null) {
    final JsonSerializer ser = factory.createSerializer();
    return new JsonSerializer() {

      @SuppressWarnings("unchecked")
      @Override
      public void serialize(Object o, JsonGenerator gen, SerializerProvider serializerProvider)
          throws IOException {

        gen.writeStartArray();
        gen.setCurrentValue(o);

        int length = Array.getLength(o);
        for (int i = 0; i < length; i++) {
          Object arrayElement = Array.get(o, i);
          ser.serialize(arrayElement, gen, serializerProvider);
        }

        gen.writeEndArray();
      }
    };
  }

  return super.findArraySerializer(config, type, beanDesc, elementTypeSerializer, elementValueSerializer);
}
 
Example 14
Source File: Tuple6Serializer.java    From cyclops with Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(Tuple6<?,?,?,?,?,?> value, JsonGenerator gen, SerializerProvider serializers) throws IOException {

  Object[] array = new Object[]{value._1(),value._2(),value._3(),value._4(),value._5(),value._6()};
  gen.writeStartArray();
  for(Object o : array) {
    JsonSerializer<Object> ser = serializers.findTypedValueSerializer(o.getClass(),true,null);
    ser.serialize(o, gen, serializers);
  }
  gen.writeEndArray();
}
 
Example 15
Source File: Tuple8Serializer.java    From cyclops with Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(Tuple8<?,?,?,?,?,?,?,?> value, JsonGenerator gen, SerializerProvider serializers) throws IOException {

  Object[] array = new Object[]{value._1(),value._2(),value._3(),value._4(),value._5(),value._6(),value._7(),value._8()};
  gen.writeStartArray();
  for(Object o : array) {
    JsonSerializer<Object> ser = serializers.findTypedValueSerializer(o.getClass(),true,null);
    ser.serialize(o, gen, serializers);
  }
  gen.writeEndArray();
}
 
Example 16
Source File: ResourcesMapper.java    From mobilecloud-15 with Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(Resources value, JsonGenerator jgen,
		SerializerProvider provider) throws IOException,
		JsonProcessingException {
	// Extracted the actual data inside of the Resources object
	// that we care about (e.g., the list of Video objects)
	Object content = value.getContent();
	// Instead of all of the Resources member variables, etc.
	// Just mashall the actual content (Videos) into the JSON
	JsonSerializer<Object> s = provider.findValueSerializer(
			content.getClass(), null);
	s.serialize(content, jgen, provider);
}
 
Example 17
Source File: JacksonJsonMessageSerializerTest.java    From log4j2-elasticsearch with Apache License 2.0 4 votes vote down vote up
@Test
public void serializerWritesRawValue() throws IOException {

    // given
    JsonSerializer<Message> serializer = new JacksonJsonMessageSerializer();

    Message message = mock(Message.class);

    String expectedValue = UUID.randomUUID().toString();
    when(message.getFormattedMessage()).thenReturn(expectedValue);

    JsonGenerator jsonGenerator = mock(JsonGenerator.class);

    // when
    serializer.serialize(message, jsonGenerator, mock(SerializerProvider.class));

    // then
    verify(jsonGenerator).writeRaw(eq(expectedValue));

}
 
Example 18
Source File: JsonViewSerializer.java    From json-view with GNU General Public License v3.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
void writeObject(Object obj) throws IOException {
  jgen.writeStartObject();

  List<AccessibleProperty> fields = getAccessibleProperties(obj.getClass());

  for(AccessibleProperty property : fields) {
    try {
      //if the field has a serializer annotation on it, serialize with it
      if(fieldAllowed(property, obj.getClass())) {
        Object val = readField(obj, property);
        if(!valueAllowed(property, val, obj.getClass())) {
          continue;
        }

        String name = getFieldName(property);
        jgen.writeFieldName(name);

        JsonSerializer fieldSerializer = annotatedWithJsonSerialize(property);
        if(fieldSerializer != null) {
          fieldSerializer.serialize(val, jgen, serializerProvider);
        } else if(customSerializersMap != null && val != null) {
          JsonSerializer<Object> serializer = customSerializersMap.get(val.getClass());
          if(serializer != null) {
            serializer.serialize(val, jgen, serializerProvider);
          } else {
            new JsonWriter(jgen, result, currentMatch, currentPath, path, property, serializerProvider).write(name, val);
          }
        } else if(val instanceof JsonNode) {
          // Let Jackson deal with these, they're special
          serializerProvider.defaultSerializeValue(val, jgen);
        } else {
          new JsonWriter(jgen, result, currentMatch, currentPath, path, property, serializerProvider).write(name, val);
        }
      }
    } catch(IllegalArgumentException | IllegalAccessException e) {
      throw new RuntimeException(e);
    }
  }

  jgen.writeEndObject();
}
 
Example 19
Source File: ObjectMethodPropertyWriter.java    From jackson-modules-base with Apache License 2.0 4 votes vote down vote up
@Override
public final void serializeAsElement(Object bean, JsonGenerator gen, SerializerProvider prov) throws Exception
{
    if (broken) {
        fallbackWriter.serializeAsElement(bean, gen, prov);
        return;
    }
    Object value;
    try {
        value = _propertyAccessor.objectGetter(bean, _propertyIndex);
    } catch (Throwable t) {
        _handleProblem(bean, gen, prov, t, true);
        return;
    }
    // Null (etc) handling; copied from super-class impl
    if (value == null) {
        if (_nullSerializer != null) {
            _nullSerializer.serialize(null, gen, prov);
        } else if (_suppressNulls) {
            serializeAsPlaceholder(bean, gen, prov);
        } else {
            prov.defaultSerializeNullValue(gen);
        }
        return;
    }
    JsonSerializer<Object> ser = _serializer;
    if (ser == null) {
        Class<?> cls = value.getClass();
        PropertySerializerMap map = _dynamicSerializers;
        ser = map.serializerFor(cls);
        if (ser == null) {
            ser = _findAndAddDynamic(map, cls, prov);
        }
    }
    if (_suppressableValue != null) {
        if (MARKER_FOR_EMPTY == _suppressableValue) {
            if (ser.isEmpty(prov, value)) {
                serializeAsPlaceholder(bean, gen, prov);
                return;
            }
        } else if (_suppressableValue.equals(value)) {
            serializeAsPlaceholder(bean, gen, prov);
            return;
        }
    }
    if (value == bean) {
        // three choices: exception; handled by call; or pass-through
        if (_handleSelfReference(bean, gen, prov, ser)) {
            return;
        }
    }
    if (_typeSerializer == null) {
        ser.serialize(value, gen, prov);
    } else {
        ser.serializeWithType(value, gen, prov, _typeSerializer);
    }
}
 
Example 20
Source File: CollectionSerializer.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void serializeContents(Collection<?> value, JsonGenerator g, SerializerProvider provider) throws IOException
{
    g.setCurrentValue(value);
    if (_elementSerializer != null) {
        serializeContentsUsing(value, g, provider, _elementSerializer);
        return;
    }
    Iterator<?> it = value.iterator();
    if (!it.hasNext()) {
        return;
    }
    PropertySerializerMap serializers = _dynamicSerializers;
    final TypeSerializer typeSer = _valueTypeSerializer;

    int i = 0;
    try {
        do {
            Object elem = it.next();
            if (elem == null) {
                provider.defaultSerializeNull(g);
            } else {
                Class<?> cc = elem.getClass();
                JsonSerializer<Object> serializer = serializers.serializerFor(cc);
                if (serializer == null) {
                    if (_elementType.hasGenericTypes()) {
                        serializer = _findAndAddDynamic(serializers,
                                provider.constructSpecializedType(_elementType, cc), provider);
                    } else {
                        serializer = _findAndAddDynamic(serializers, cc, provider);
                    }
                    serializers = _dynamicSerializers;
                }
                if (typeSer == null) {
                    serializer.serialize(elem, g, provider);
                } else {
                    serializer.serializeWithType(elem, g, provider, typeSer);
                }
            }
            ++i;
        } while (it.hasNext());
    } catch (Exception e) {
        wrapAndThrow(provider, e, value, i);
    }
}