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 Project: Rosetta   Author: HubSpot   File: StoredAsJsonBeanSerializerModifier.java    License: 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 #2
Source Project: lams   Author: lamsfoundation   File: ReadOnlyClassToSerializerMap.java    License: 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 #3
Source Project: jframework   Author: micro-jframework   File: BigDecimalSpecifySerialize.java    License: 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 #4
Source Project: tutorials   Author: eugenp   File: JacksonDynamicIgnoreUnitTest.java    License: 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 #5
Source Project: json-flattener   Author: wnameless   File: ObjectMapperFactory.java    License: 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 Project: dawnsci   Author: eclipse   File: MarshallerService.java    License: 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 Project: rapidoid   Author: rapidoid   File: RapidoidThingsTest.java    License: 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 #8
Source Project: lams   Author: lamsfoundation   File: ReadOnlyClassToSerializerMap.java    License: 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 #9
Source Project: botbuilder-java   Author: microsoft   File: AdditionalPropertiesSerializer.java    License: 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 #10
Source Project: kafka-webview   Author: SourceLabOrg   File: ToStringSerializer.java    License: 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 #11
Source Project: spring-cloud-netflix   Author: spring-cloud   File: RestTemplateTransportClientFactory.java    License: 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 #12
Source Project: lams   Author: lamsfoundation   File: UnwrappingBeanPropertyWriter.java    License: 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 #13
Source Project: datacollector   Author: streamsets   File: FlatRBeanSerializerModifier.java    License: Apache License 2.0 5 votes vote down vote up
public JsonSerializer<?> modifySerializer(
    SerializationConfig config,
    BeanDescription beanDesc,
    JsonSerializer<?> serializer
) {
  // Only use the serializer for any subclasses of RType
  if (RType.class.isAssignableFrom(beanDesc.getBeanClass()) && serializer instanceof BeanSerializerBase) {
    return new RBeanContextData((BeanSerializerBase) serializer);
  }
  return serializer;
}
 
Example #14
Source Project: endpoints-java   Author: cloudendpoints   File: ServletResponseResultWriter.java    License: Apache License 2.0 5 votes vote down vote up
private static SimpleModule getWriteLongAsStringModule() {
  JsonSerializer<Long> longSerializer = new JsonSerializer<Long>() {
    @Override
    public void serialize(Long value, JsonGenerator jgen, SerializerProvider provider)
        throws IOException {
      jgen.writeString(value.toString());
    }
  };
  SimpleModule writeLongAsStringModule = new SimpleModule("writeLongAsStringModule",
      new Version(1, 0, 0, null, null, null));
  writeLongAsStringModule.addSerializer(Long.TYPE, longSerializer);  // long (primitive)
  writeLongAsStringModule.addSerializer(Long.class, longSerializer); // Long (class)
  return writeLongAsStringModule;
}
 
Example #15
Source Project: jackson-datatypes-collections   Author: FasterXML   File: HppcSerializers.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Anything that we don't explicitly mark as Map- or Collection-like
 * will end up here...
 */
@Override
public JsonSerializer<?> findSerializer(SerializationConfig config,
        JavaType type, BeanDescription beanDesc, JsonFormat.Value formatOverrides)
{
    return HppcContainerSerializers.getMatchingSerializer(config, type);
}
 
Example #16
Source Project: jackson-modules-base   Author: FasterXML   File: BooleanMethodPropertyWriter.java    License: 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 #17
Source Project: log4j2-elasticsearch   Author: rfoltyns   File: JacksonHandlerInstantiatorTest.java    License: 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 #18
Source Project: lams   Author: lamsfoundation   File: PropertySerializerMap.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public JsonSerializer<Object> serializerFor(Class<?> type)
{
    for (int i = 0, len = _entries.length; i < len; ++i) {
        TypeAndSerializer entry = _entries[i];
        if (entry.type == type) {
            return entry.serializer;
        }
    }
    return null;
}
 
Example #19
Source Project: simple-spring-memcached   Author: ragnor   File: JsonObjectMapper.java    License: MIT License 5 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
public void setSerializers(final Map<Class<?>, JsonSerializer<?>> serializers) {
    for (Map.Entry<Class<?>, JsonSerializer<?>> entry : serializers.entrySet()) {
        module.addSerializer((Class) entry.getKey(), entry.getValue());
    }

    // required otherwise new serializers are not registered to context
    registerModule(module);
}
 
Example #20
Source Project: quilt   Author: hyperledger   File: InterledgerSerializers.java    License: 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 #21
Source Project: simple-spring-memcached   Author: ragnor   File: JsonObjectMapper.java    License: 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 #22
Source Project: java-technology-stack   Author: codeEngraver   File: Jackson2ObjectMapperBuilderTests.java    License: 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 #23
Source Project: spring4-understanding   Author: langtianya   File: Jackson2ObjectMapperFactoryBeanTests.java    License: 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 #24
Source Project: jackson-datatypes-collections   Author: FasterXML   File: RefRefMapIterableSerializer.java    License: 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 #25
Source Project: endpoints-java   Author: cloudendpoints   File: ServletResponseResultWriter.java    License: 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 #26
Source Project: jackson-modules-base   Author: FasterXML   File: IntMethodPropertyWriter.java    License: 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 #27
Source Project: Rosetta   Author: HubSpot   File: RosettaObjectMapperTest.java    License: 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 #28
Source Project: lams   Author: lamsfoundation   File: ReadOnlyClassToSerializerMap.java    License: 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 Project: endpoints-java   Author: cloudendpoints   File: ApiAnnotationIntrospector.java    License: 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 Project: alfresco-remote-api   Author: Alfresco   File: RestJsonModule.java    License: 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());
        }
    }
}