com.fasterxml.jackson.databind.JsonSerializer Java Examples

The following examples show how to use com.fasterxml.jackson.databind.JsonSerializer. 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: ReadOnlyClassToSerializerMap.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public JsonSerializer<Object> untypedValueSerializer(JavaType type)
{
    Bucket bucket = _buckets[TypeKey.untypedHash(type) & _mask];
    if (bucket == null) {
        return null;
    }
    if (bucket.matchesUntyped(type)) {
        return bucket.value;
    }
    while ((bucket = bucket.next) != null) {
        if (bucket.matchesUntyped(type)) {
            return bucket.value;
        }
    }
    return null;
}
 
Example #2
Source File: BigDecimalSpecifySerialize.java    From jframework with Apache License 2.0 6 votes vote down vote up
@Override
public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException {
    // 为空直接跳过
    if (property == null) {
        return prov.findNullValueSerializer(property);
    }
    // 非 BigDecimal 类直接跳过
    if (Objects.equals(property.getType().getRawClass(), BigDecimal.class)) {
        BigDecimalSpecify doubleSpecify = property.getAnnotation(BigDecimalSpecify.class);
        if (doubleSpecify == null) {
            doubleSpecify = property.getContextAnnotation(BigDecimalSpecify.class);
        }
        // 如果能得到注解,就将注解的 value 传入 BigDecimalSpecifySerialize
        if (doubleSpecify != null) {
            return new BigDecimalSpecifySerialize(doubleSpecify.value());
        }
    }
    return prov.findValueSerializer(property.getType(), property);
}
 
Example #3
Source File: ToStringSerializer.java    From kafka-webview with MIT License 6 votes vote down vote up
@Override
public void serialize(
    final Object value,
    final JsonGenerator gen,
    final SerializerProvider serializers
) throws IOException {
    if (value == null) {
        gen.writeString("");
        return;
    }

    // See if we have a serializer that is NOT the unknown serializer
    final JsonSerializer serializer = serializers.findValueSerializer(value.getClass());
    if (serializer != null && !(serializer instanceof UnknownSerializer)) {
        serializer.serialize(value, gen, serializers);
        return;
    }
    gen.writeString(value.toString());
}
 
Example #4
Source File: RestTemplateTransportClientFactory.java    From spring-cloud-netflix with Apache License 2.0 6 votes vote down vote up
public static BeanSerializerModifier createJsonSerializerModifier() { // final
	// KeyFormatter
	// keyFormatter,
	// final
	// boolean
	// compactMode)
	// {
	return new BeanSerializerModifier() {
		@Override
		public JsonSerializer<?> modifySerializer(SerializationConfig config,
				BeanDescription beanDesc, JsonSerializer<?> serializer) {
			/*
			 * if (beanDesc.getBeanClass().isAssignableFrom(Applications.class)) {
			 * return new ApplicationsJsonBeanSerializer((BeanSerializerBase)
			 * serializer, keyFormatter); }
			 */
			if (beanDesc.getBeanClass().isAssignableFrom(InstanceInfo.class)) {
				return new InstanceInfoJsonBeanSerializer(
						(BeanSerializerBase) serializer, false);
			}
			return serializer;
		}
	};
}
 
Example #5
Source File: ObjectMapperFactory.java    From json-flattener with Apache License 2.0 6 votes vote down vote up
public static ObjectMapper getWriter() {
  ObjectMapper mapper = new ObjectMapper();

  JsonSerializer<String> js = new JsonSerializer<String>() {

    @Override
    public void serialize(String value, JsonGenerator gen,
        SerializerProvider serializers) throws IOException {
      gen.writeRawValue("\"" + value + "\"");
    }

  };
  SimpleModule module = new SimpleModule();
  module.addSerializer(String.class, js);
  mapper.registerModule(module);

  return mapper;
}
 
Example #6
Source File: MarshallerService.java    From dawnsci with Eclipse Public License 1.0 6 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
private void applyMarshallersToModule(SimpleModule module, List<IMarshaller> marshallers) throws InstantiationException, IllegalAccessException {
	for (IMarshaller marshaller : marshallers) {
		Class<?> objectClass = marshaller.getObjectClass();
		if (objectClass!=null) {
			module.addSerializer(objectClass,  (JsonSerializer)marshaller.getSerializerClass().newInstance());
			module.addDeserializer(objectClass,(JsonDeserializer)marshaller.getDeserializerClass().newInstance());
		}

		Class<?> mixInType  = marshaller.getMixinAnnotationType();
		Class<?> mixInClass = marshaller.getMixinAnnotationClass();
		if (mixInClass!=null && mixInType!=null) {
			module.setMixInAnnotation(mixInType, mixInClass);
		}
	}
}
 
Example #7
Source File: JacksonDynamicIgnoreUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Before
public void setUp() {
    mapper.setSerializationInclusion(Include.NON_EMPTY);
    mapper.registerModule(new SimpleModule() {
        @Override
        public void setupModule(final SetupContext context) {
            super.setupModule(context);
            context.addBeanSerializerModifier(new BeanSerializerModifier() {
                @Override
                public JsonSerializer<?> modifySerializer(final SerializationConfig config, final BeanDescription beanDesc, final JsonSerializer<?> serializer) {
                    if (Hidable.class.isAssignableFrom(beanDesc.getBeanClass())) {
                        return new HidableSerializer((JsonSerializer<Object>) serializer);
                    }
                    return serializer;
                }
            });
        }
    });
}
 
Example #8
Source File: AdditionalPropertiesSerializer.java    From botbuilder-java with MIT License 6 votes vote down vote up
/**
 * Gets a module wrapping this serializer as an adapter for the Jackson
 * ObjectMapper.
 *
 * @param mapper the object mapper for default serializations
 * @return a simple module to be plugged onto Jackson ObjectMapper.
 */
public static SimpleModule getModule(final ObjectMapper mapper) {
    SimpleModule module = new SimpleModule();
    module.setSerializerModifier(new BeanSerializerModifier() {
        @Override
        public JsonSerializer<?> modifySerializer(SerializationConfig config, BeanDescription beanDesc, JsonSerializer<?> serializer) {
            for (Class<?> c : TypeToken.of(beanDesc.getBeanClass()).getTypes().classes().rawTypes()) {
                if (c.isAssignableFrom(Object.class)) {
                    continue;
                }
                Field[] fields = c.getDeclaredFields();
                for (Field field : fields) {
                    if ("additionalProperties".equalsIgnoreCase(field.getName())) {
                        JsonProperty property = field.getAnnotation(JsonProperty.class);
                        if (property != null && property.value().isEmpty()) {
                            return new AdditionalPropertiesSerializer(beanDesc.getBeanClass(), serializer, mapper);
                        }
                    }
                }
            }
            return serializer;
        }
    });
    return module;
}
 
Example #9
Source File: ReadOnlyClassToSerializerMap.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public JsonSerializer<Object> typedValueSerializer(JavaType type)
{
    Bucket bucket = _buckets[TypeKey.typedHash(type) & _mask];
    if (bucket == null) {
        return null;
    }
    if (bucket.matchesTyped(type)) {
        return bucket.value;
    }
    while ((bucket = bucket.next) != null) {
        if (bucket.matchesTyped(type)) {
            return bucket.value;
        }
    }
    return null;
}
 
Example #10
Source File: RapidoidThingsTest.java    From rapidoid with Apache License 2.0 6 votes vote down vote up
@Test
public void classesShouldExtendRapidoidThing() {
	for (String cls : Cls.getRapidoidClasses()) {

		if (cls.startsWith("org.rapidoid.plugin.app.")
			|| cls.startsWith("org.rapidoid.test.")) continue;

		Class<?> clazz = Cls.get(cls);

		if (!clazz.isInterface() && !clazz.isEnum() && !clazz.isAnnotation()) {
			U.must(RapidoidThing.class.isAssignableFrom(clazz)
				|| clazz == TestCommons.class
				|| Exception.class.isAssignableFrom(clazz)
				|| ClassLoader.class.isAssignableFrom(clazz)
				|| HibernatePersistenceProvider.class.isAssignableFrom(clazz)
				|| OutputStream.class.isAssignableFrom(clazz)
				|| Map.class.isAssignableFrom(clazz)
				|| JsonSerializer.class.isAssignableFrom(clazz)
				|| JsonDeserializer.class.isAssignableFrom(clazz)
				|| LogFactory.class.isAssignableFrom(clazz)
				|| Thread.class.isAssignableFrom(clazz), "" + cls);
		}
	}
}
 
Example #11
Source File: UnwrappingBeanPropertyWriter.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void depositSchemaProperty(final JsonObjectFormatVisitor visitor,
        SerializerProvider provider) throws JsonMappingException
{
    JsonSerializer<Object> ser = provider
            .findValueSerializer(this.getType(), this)
            .unwrappingSerializer(_nameTransformer);

    if (ser.isUnwrappingSerializer()) {
        ser.acceptJsonFormatVisitor(new JsonFormatVisitorWrapper.Base(provider) {
            // an unwrapping serializer will always expect ObjectFormat,
            // hence, the other cases do not have to be implemented
            @Override
            public JsonObjectFormatVisitor expectObjectFormat(JavaType type)
                    throws JsonMappingException {
                return visitor;
            }
        }, this.getType());
    } else {
        super.depositSchemaProperty(visitor, provider);
    }
}
 
Example #12
Source File: StoredAsJsonBeanSerializerModifier.java    From Rosetta with Apache License 2.0 6 votes vote down vote up
@Override
public List<BeanPropertyWriter> changeProperties(SerializationConfig config, BeanDescription beanDesc, List<BeanPropertyWriter> beanProperties) {
  for (BeanPropertyWriter beanProperty : beanProperties) {
    StoredAsJson storedAsJson = beanProperty.getAnnotation(StoredAsJson.class);
    if (storedAsJson != null && !StoredAsJson.NULL.equals(storedAsJson.empty())) {
      final JsonSerializer<Object> nullSerializer;
      if (storedAsJson.binary()) {
        nullSerializer = new ConstantBinarySerializer(storedAsJson.empty());
      } else {
        nullSerializer = new ConstantSerializer(storedAsJson.empty());
      }

      beanProperty.assignNullSerializer(nullSerializer);
    }
  }

  return super.changeProperties(config, beanDesc, beanProperties);
}
 
Example #13
Source File: JacksonHandlerInstantiatorTest.java    From log4j2-elasticsearch with Apache License 2.0 5 votes vote down vote up
@Test
public void serializerInstanceReturnsNull() {

    // given
    VirtualProperty[] customProperties = new VirtualProperty[0];
    Log4j2Lookup valueResolver = new Log4j2Lookup(null);
    JacksonHandlerInstantiator handlerInstantiator = createTestHandlerInstantiator(customProperties, valueResolver);

    // when
    JsonSerializer<?> result = handlerInstantiator.serializerInstance(null, null, null);

    // then
    Assert.assertNull(result);

}
 
Example #14
Source File: Main.java    From microservices-comparison with Apache License 2.0 5 votes vote down vote up
private static ObjectMapper createObjectMapper() {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
        @Override
        public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException {
        }
    });
    objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    return objectMapper;
}
 
Example #15
Source File: JsonObjectMapper.java    From simple-spring-memcached with MIT License 5 votes vote down vote up
public void setSerializers(final List<JsonSerializer<?>> serializers) {
    for (JsonSerializer<?> serializer : serializers) {
        module.addSerializer(serializer);
    }

    // required otherwise new serializers are not registered to context
    registerModule(module);
}
 
Example #16
Source File: InterledgerSerializers.java    From quilt with Apache License 2.0 5 votes vote down vote up
@Override
public JsonSerializer<?> findSerializer(
    SerializationConfig config, JavaType type, BeanDescription beanDesc
) {
  final Class<?> raw = type.getRawClass();
  if (InterledgerAddress.class.isAssignableFrom(raw)) {
    return InterledgerAddressSerializer.INSTANCE;
  }
  if (InterledgerAddressPrefix.class.isAssignableFrom(raw)) {
    return new InterledgerAddressPrefixSerializer();
  }
  if (InterledgerCondition.class.isAssignableFrom(raw)) {
    return new ConditionSerializer(cryptoConditionEncoding);
  }
  if (InterledgerFulfillment.class.isAssignableFrom(raw)) {
    return new FulfillmentSerializer(cryptoConditionEncoding);
  }
  if (SharedSecret.class.isAssignableFrom(raw)) {
    return new SharedSecretSerializer();
  }
  if (LinkId.class.isAssignableFrom(raw)) {
    return new LinkIdSerializer();
  }
  if (LinkType.class.isAssignableFrom(raw)) {
    return new LinkTypeSerializer();
  }

  return null;
}
 
Example #17
Source File: Jackson2ObjectMapperBuilderTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void serializerByType() {
	JsonSerializer<Number> serializer = new NumberSerializer(Integer.class);
	ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json()
			.modules(new ArrayList<>())  // Disable well-known modules detection
			.serializerByType(Boolean.class, serializer)
			.build();
	assertTrue(getSerializerFactoryConfig(objectMapper).hasSerializers());
	Serializers serializers = getSerializerFactoryConfig(objectMapper).serializers().iterator().next();
	assertSame(serializer, serializers.findSerializer(null, SimpleType.construct(Boolean.class), null));
}
 
Example #18
Source File: ConfigDefSerializationModule.java    From connect-utils with Apache License 2.0 5 votes vote down vote up
public ConfigDefSerializationModule() {
  super();
  addSerializer(Password.class, new Serializer());
  addDeserializer(Password.class, new Deserializer());
  addSerializer(ConfigDef.Validator.class, new JsonSerializer<ConfigDef.Validator>() {
    @Override
    public void serialize(ConfigDef.Validator validator, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
      jsonGenerator.writeString(validator.toString());
    }
  });
}
 
Example #19
Source File: VavrSerializers.java    From vavr-jackson with Apache License 2.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) {
    Class<?> raw = type.getRawClass();
    if (Map.class.isAssignableFrom(raw)) {
        return new MapSerializer(type);
    }
    if (Multimap.class.isAssignableFrom(raw)) {
        return new MultimapSerializer(type);
    }
    return super.findMapLikeSerializer(config, type, beanDesc, keySerializer, elementTypeSerializer, elementValueSerializer);
}
 
Example #20
Source File: BooleanMethodPropertyWriter.java    From jackson-modules-base with Apache License 2.0 5 votes vote down vote up
public BooleanMethodPropertyWriter(BeanPropertyWriter src, BeanPropertyAccessor acc, int index,
        JsonSerializer<Object> ser) {
    super(src, acc, index, ser);

    if (_suppressableValue instanceof Boolean) {
        _suppressableBoolean = ((Boolean)_suppressableValue).booleanValue();
        _suppressableSet = true;
    } else {
        _suppressableBoolean = false;
        _suppressableSet = false;
    }
}
 
Example #21
Source File: Jackson2ObjectMapperFactoryBeanTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void settingNullValuesShouldNotThrowExceptions() {
	this.factory.setSerializers((JsonSerializer<?>[]) null);
	this.factory.setSerializersByType(null);
	this.factory.setDeserializersByType(null);
	this.factory.setFeaturesToEnable((Object[]) null);
	this.factory.setFeaturesToDisable((Object[]) null);
}
 
Example #22
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 #23
Source File: ServletResponseResultWriter.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
private static SimpleModule getWriteDateAsStringModule() {
  JsonSerializer<Date> dateSerializer = new JsonSerializer<Date>() {
    @Override
    public void serialize(Date value, JsonGenerator jgen, SerializerProvider provider)
        throws IOException {
      jgen.writeString(new com.google.api.client.util.DateTime(value).toStringRfc3339());
    }
  };
  SimpleModule writeDateAsStringModule = new SimpleModule("writeDateAsStringModule",
      new Version(1, 0, 0, null, null, null));
  writeDateAsStringModule.addSerializer(Date.class, dateSerializer);
  return writeDateAsStringModule;
}
 
Example #24
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 #25
Source File: IntMethodPropertyWriter.java    From jackson-modules-base with Apache License 2.0 5 votes vote down vote up
public IntMethodPropertyWriter(BeanPropertyWriter src, BeanPropertyAccessor acc, int index,
        JsonSerializer<Object> ser) {
    super(src, acc, index, ser);

    if (_suppressableValue instanceof Integer) {
        _suppressableInt = (Integer)_suppressableValue;
        _suppressableIntSet = true;
    } else {
        _suppressableInt = 0;
        _suppressableIntSet = false;
    }
}
 
Example #26
Source File: RosettaObjectMapperTest.java    From Rosetta with Apache License 2.0 5 votes vote down vote up
private static void registerSerializer(ConfigRegistry config, JsonSerializer<TestObject> serializer) {
  ObjectMapper objectMapper = new ObjectMapper();
  SimpleModule module = new SimpleModule();
  module.setSerializers(new SimpleSerializers(Collections.singletonList(serializer)));
  objectMapper.registerModule(module);

  config.get(RosettaObjectMapper.class).setObjectMapper(objectMapper);
}
 
Example #27
Source File: JacksonTest.java    From albedo with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void testAddExtraField() throws Exception {
	ObjectMapper mapper = new ObjectMapper();

	mapper.registerModule(new SimpleModule() {

		public void setupModule(SetupContext context) {
			super.setupModule(context);

			context.addBeanSerializerModifier(new BeanSerializerModifier() {

				public JsonSerializer<?> modifySerializer(
					SerializationConfig config,
					BeanDescription beanDesc,
					JsonSerializer<?> serializer) {
					if (serializer instanceof BeanSerializerBase) {
						return new ExtraFieldSerializer(
							(BeanSerializerBase) serializer);
					}
					return serializer;

				}
			});
		}
	});

	mapper.writeValue(System.out, Lists.newArrayList(new MyClass1(), new MyClass2()));
	//prints {"classField":"classFieldValue","extraField":"extraFieldValue"}
}
 
Example #28
Source File: ReadOnlyClassToSerializerMap.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public Bucket(Bucket next, TypeKey key, JsonSerializer<Object> value)
{
    this.next = next;
    this.value = value;
    _isTyped = key.isTyped();
    _class = key.getRawType();
    _type = key.getType();
}
 
Example #29
Source File: ApiAnnotationIntrospector.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
@Nullable
private static <TFrom, TTo> JsonSerializer<TFrom> getJsonSerializer(
    @Nullable final Transformer<TFrom, TTo> serializer) {
  if (serializer == null) {
    return null;
  }
  return new JsonSerializer<TFrom>() {
    @Override
    public void serialize(TFrom value, JsonGenerator jgen, SerializerProvider provider)
        throws IOException {
      jgen.writeObject(serializer.transformTo(value));
    }
  };
}
 
Example #30
Source File: RestJsonModule.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public void afterPropertiesSet() throws Exception
{
    if (jsonSerializers != null) 
    {
        if (logger.isDebugEnabled())
        {
            logger.debug("Setting up Json Module serializers");
        }
        for (JsonSerializer aSerializer : jsonSerializers)
        {
            addSerializer(aSerializer);
        }
    }
    if (jsonDeserializers != null) 
    {
        if (logger.isDebugEnabled())
        {
            logger.debug("Setting up Json Module deserializers");
        }
        for (Entry<String, JsonDeserializer> aDeserializer : jsonDeserializers.entrySet())
        {
            Class theDeserializer = Class.forName(aDeserializer.getKey());
            addDeserializer(theDeserializer, aDeserializer.getValue());
        }
    }
}