Java Code Examples for com.fasterxml.jackson.databind.ObjectMapper#activateDefaultTyping()

The following examples show how to use com.fasterxml.jackson.databind.ObjectMapper#activateDefaultTyping() . 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: RedisTemplateConfiguration.java    From mica with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * value 值 序列化
 *
 * @return RedisSerializer
 */
@Bean
@ConditionalOnMissingBean(RedisSerializer.class)
public RedisSerializer<Object> redisSerializer(MicaRedisProperties properties,
											   ObjectProvider<ObjectMapper> objectProvider) {
	MicaRedisProperties.SerializerType serializerType = properties.getSerializerType();
	if (MicaRedisProperties.SerializerType.JDK == serializerType) {
		return new JdkSerializationRedisSerializer();
	}
	// jackson findAndRegisterModules,use copy
	ObjectMapper objectMapper = objectProvider.getIfAvailable(ObjectMapper::new).copy();
	// findAndRegisterModules
	objectMapper.findAndRegisterModules();
	// class type info to json
	GenericJackson2JsonRedisSerializer.registerNullValueSerializer(objectMapper, null);
	objectMapper.activateDefaultTyping(objectMapper.getPolymorphicTypeValidator(), DefaultTyping.NON_FINAL, As.PROPERTY);
	return new GenericJackson2JsonRedisSerializer(objectMapper);
}
 
Example 2
Source File: FebsLettuceRedisAutoConfigure.java    From FEBS-Cloud with Apache License 2.0 6 votes vote down vote up
@Bean(name = "redisTemplate")
@ConditionalOnClass(RedisOperations.class)
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
    RedisTemplate<String, Object> template = new RedisTemplate<>();
    template.setConnectionFactory(factory);

    Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
    ObjectMapper mapper = new ObjectMapper();
    mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    mapper.activateDefaultTyping(mapper.getPolymorphicTypeValidator(), ObjectMapper.DefaultTyping.NON_FINAL);
    jackson2JsonRedisSerializer.setObjectMapper(mapper);

    StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
    template.setKeySerializer(stringRedisSerializer);
    template.setHashKeySerializer(stringRedisSerializer);
    template.setValueSerializer(jackson2JsonRedisSerializer);
    template.setHashValueSerializer(jackson2JsonRedisSerializer);
    template.afterPropertiesSet();

    return template;
}
 
Example 3
Source File: RedisConfig.java    From hdw-dubbo with Apache License 2.0 6 votes vote down vote up
@Bean
public RedisSerializer<Object> redisSerializer() {
    //创建JSON序列化器
    Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer =
            new Jackson2JsonRedisSerializer<>(Object.class);
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    objectMapper.configure(MapperFeature.USE_ANNOTATIONS, false);
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    //TODO: 此项必须配置,否则会报java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to XXX
    objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance ,
            ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
    return jackson2JsonRedisSerializer;
}
 
Example 4
Source File: RedisConfigure.java    From cms with Apache License 2.0 6 votes vote down vote up
/**
 * json序列化
 *
 * @return
 */
@Bean
public RedisSerializer<Object> jackson2JsonRedisSerializer() {
    //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
    Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer(Object.class);

    ObjectMapper objectMapper = new ObjectMapper();
    // 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
    objectMapper.setVisibility(PropertyAccessor.ALL, Visibility.ANY);
    // 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常
    //objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    objectMapper.activateDefaultTyping(objectMapper.getPolymorphicTypeValidator(), ObjectMapper.DefaultTyping.NON_FINAL, As.WRAPPER_ARRAY);

    serializer.setObjectMapper(objectMapper);
    return serializer;
}
 
Example 5
Source File: RedisConfig.java    From fw-spring-cloud with Apache License 2.0 5 votes vote down vote up
@Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
	StringRedisTemplate template = new StringRedisTemplate(factory);
	Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(
			Object.class);
	ObjectMapper om = new ObjectMapper();
	om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
	om.activateDefaultTyping(om.getPolymorphicTypeValidator(), ObjectMapper.DefaultTyping.NON_FINAL);
	jackson2JsonRedisSerializer.setObjectMapper(om);
	template.setKeySerializer(myStringSerializer);
	template.setHashKeySerializer(myStringSerializer);
	template.setValueSerializer(jackson2JsonRedisSerializer);
	template.afterPropertiesSet();
	return template;
}
 
Example 6
Source File: RedisConfig.java    From ueboot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean(type = {"org.springframework.data.redis.core.RedisTemplate"})
public RedisTemplate<?, ?> redisTemplate(
        LettuceConnectionFactory redisConnectionFactory) {
    StringRedisTemplate template = new StringRedisTemplate(redisConnectionFactory);
    Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
    ObjectMapper om = new ObjectMapper();
    om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    om.activateDefaultTyping(BasicPolymorphicTypeValidator.builder().build(),ObjectMapper.DefaultTyping.NON_FINAL);
    jackson2JsonRedisSerializer.setObjectMapper(om);
    template.setValueSerializer(jackson2JsonRedisSerializer);
    template.setConnectionFactory(redisConnectionFactory);
    template.afterPropertiesSet();
    return template;
}
 
Example 7
Source File: RedisCacheConfig.java    From iot-dc3 with Apache License 2.0 5 votes vote down vote up
/**
 * 自定义 RedisCacheManager 类,主要是设置序列化,解决乱码问题
 *
 * @param factory RedisConnectionFactory
 * @return CacheManager
 */
@Bean
public CacheManager cacheManager(RedisConnectionFactory factory) {
    Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
    // 解决查询缓存转换异常的问题
    ObjectMapper om = new ObjectMapper();
    om.activateDefaultTyping(om.getPolymorphicTypeValidator(), ObjectMapper.DefaultTyping.NON_FINAL);
    jackson2JsonRedisSerializer.setObjectMapper(om);
    // 配置序列化(解决乱码的问题)
    RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
            .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
            .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
            .disableCachingNullValues().entryTtl(timeToLive);
    return RedisCacheManager.builder(factory).cacheDefaults(config).build();
}
 
Example 8
Source File: V2_35_2__Update_data_sync_job_parameters_with_system_setting_value.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public V2_35_2__Update_data_sync_job_parameters_with_system_setting_value()
{
    ObjectMapper mapper = new ObjectMapper();
    mapper.activateDefaultTyping( BasicPolymorphicTypeValidator.builder().allowIfBaseType( JobParameters.class ).build() );
    mapper.setSerializationInclusion( JsonInclude.Include.NON_NULL );

    JavaType resultingJavaType = mapper.getTypeFactory().constructType( JobParameters.class );
    reader = mapper.readerFor( resultingJavaType );
    writer = mapper.writerFor( resultingJavaType );
}
 
Example 9
Source File: CacheConfig.java    From platform with Apache License 2.0 5 votes vote down vote up
/**
 * RedisCacheConfiguration
 * 自定义配置,支持缓存使用Json文本格式
 *
 * @return {@link RedisCacheConfiguration}
 */
@Bean
public RedisCacheConfiguration redisCacheConfiguration() {

    // ObjectMapper & GenericJackson2JsonRedisSerializer
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    objectMapper.configure(SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS, false);
    objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    objectMapper.configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, false);
    objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);
    // LocalDateTime && LocalDate
    objectMapper.registerModule(new JavaTimeModule());

    GenericJackson2JsonRedisSerializer serializer = new GenericJackson2JsonRedisSerializer(objectMapper);

    // RedisCacheConfiguration
    RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
    config = config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(serializer));

    CacheProperties.Redis redisProperties = cacheProperties.getRedis();
    if (redisProperties.getTimeToLive() != null) {
        config = config.entryTtl(redisProperties.getTimeToLive());
    }
    if (redisProperties.getKeyPrefix() != null) {
        config = config.prefixCacheNameWith(redisProperties.getKeyPrefix());
    }
    if (!redisProperties.isCacheNullValues()) {
        config = config.disableCachingNullValues();
    }
    if (!redisProperties.isUseKeyPrefix()) {
        config = config.disableKeyPrefix();
    }

    return config;
}
 
Example 10
Source File: V2_34_7__Convert_push_analysis_job_parameters_into_list_of_string.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public void migrate( Context context ) throws Exception
{
    String pushAnalysisUid = null;

    try ( Statement statement = context.getConnection().createStatement() )
    {
        ResultSet resultSet = statement.executeQuery( "select jsonbjobparameters->1->'pushAnalysis' from public.jobconfiguration where jobtype = '" +
            JobType.PUSH_ANALYSIS.name() + "';" );

        if ( resultSet.next() )
        {
            pushAnalysisUid = resultSet.getString( 1 );
            pushAnalysisUid = StringUtils.strip( pushAnalysisUid, "\"" );
        }
    }

    if ( pushAnalysisUid != null )
    {
        ObjectMapper mapper = new ObjectMapper();
        mapper.activateDefaultTyping( BasicPolymorphicTypeValidator.builder().allowIfBaseType( JobParameters.class ).build() );
        mapper.setSerializationInclusion( JsonInclude.Include.NON_NULL );

        JavaType resultingJavaType = mapper.getTypeFactory().constructType( JobParameters.class );
        ObjectWriter writer = mapper.writerFor( resultingJavaType );

        try ( PreparedStatement ps = context.getConnection().prepareStatement( "UPDATE jobconfiguration SET jsonbjobparameters = ? where  jobtype = ?;" ) )
        {
            PushAnalysisJobParameters jobParameters = new PushAnalysisJobParameters( pushAnalysisUid );

            PGobject pg = new PGobject();
            pg.setType( "jsonb" );
            pg.setValue( writer.writeValueAsString( jobParameters ) );

            ps.setObject( 1, pg );
            ps.setString( 2, JobType.PUSH_ANALYSIS.name() );

            ps.execute();

            log.info( "JobType " + JobType.PUSH_ANALYSIS.name() + " has been updated." );
        }
    }
}