代码先锋网 代码片段及技术文章聚合

Jackson对泛型的序列化和反序列化方法汇总

技术标签: ...♣java相关  jackson

转载自:https://www.cnblogs.com/EasonJim/p/7919422.html

说明:Jackson对于简单泛型是可以正常操作的,但是如果对于太过于复杂的泛型类有时会不成功。目前还在找着更合适的Json库。不过这一点在dotnet原生方案JavaScriptSerializer可以完美解决这一些问题,无论泛型多复杂。

例子如下:

package com.jsoft.springboottest.springboottest1.controller;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jsoft.springboottest.springboottest1.Pager;
import com.jsoft.springboottest.springboottest1.PagerAppoint;
import com.jsoft.springboottest.springboottest1.User;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl;

@RestController
public class TestController {

    private static final Logger logger = LoggerFactory.getLogger(TestController.class);

    @RequestMapping("/show")
    public String show() throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        User user = new User();
        user.setId(1);
        Pager<User> pager = new Pager<User>();
        List<User> users = new ArrayList<User>();
        users.add(user);
        pager.setDatas(users);
        String json = mapper.writeValueAsString(pager);
        // 方式1
        Pager<User> userPager1 = mapper.readValue(json, new TypeReference<Pager<User>>() {
        });
        // 方式2
        Type[] types = new Type[1];
        types[0] = User.class;
        final ParameterizedTypeImpl type = ParameterizedTypeImpl.make(Pager.class, types, Pager.class.getDeclaringClass());
        TypeReference typeReference = new TypeReference<Pager>() {
            @Override
            public Type getType() {
                return type;
            }
        };
        Pager<User> userPager2 = mapper.readValue(json, typeReference);
        // 方式3
        JavaType javaType = mapper.getTypeFactory().constructParametrizedType(Pager.class, Pager.class, User.class);
        Pager<User> userPager3 = mapper.readValue(json, javaType);
        // 方式4
        JavaType javaType1 = mapper.getTypeFactory().constructParametricType(Pager.class, User.class);
        Pager<User> userPager4 = mapper.readValue(json, javaType1);
        // 方式5,新建另一个指定具体泛型T的参数的类
        PagerAppoint userPager5 = mapper.readValue(json, PagerAppoint.class);
        // 数组泛型的序列化和反序列化
        String json1 = mapper.writeValueAsString(users);
        JavaType javaType2 = mapper.getTypeFactory().constructParametricType(List.class, User.class);
        List<User> users1 = mapper.readValue(json1, javaType2);
        // HashMap
        Map<String, User> map = new HashMap<String, User>(16);
        map.put("test", user);
        String json2 = mapper.writeValueAsString(map);
        // 1
        Map<String, User> users2 = mapper.readValue(json2, new TypeReference<Map<String, User>>() {
        });
        // 2
        JavaType javaType3 = mapper.getTypeFactory().constructParametricType(HashMap.class, String.class, User.class);
        Map<String, User> users3 = mapper.readValue(json2, javaType3);

        return "hello world";
    }
}

示例工程:https://github.com/easonjim/5_java_example/tree/master/springboottest/springboottest10

参考:

http://www.yiibai.com/jackson/jackson_data_binding_generics.html

http://blog.csdn.net/z69183787/article/details/46235905

http://bbs.csdn.net/topics/391823803

https://www.cnblogs.com/quanyongan/archive/2013/04/16/3024993.html

http://www.hankcs.com/program/json-to-map-java-demo-code.html

http://huangyunbin.iteye.com/blog/2352243

http://www.jianshu.com/p/ca03c2fe36e3

http://www.yiibai.com/jackson/jackson_data_binding_generics.html

http://bbs.csdn.net/topics/391823803

https://www.cnblogs.com/quanyongan/archive/2013/04/16/3024993.html

版权声明:本文为tuzongxun原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/tuzongxun/article/details/107411790

智能推荐

Jackson序列化丢失泛型

经过 项目中遇到一个奇怪的bug,即一个Map<Integer,List<Integer>>的泛型map,向map中get一个存在的key,事实上却返回null。 经过排查,发现是该map被Jackson序列化后,key的类型从Integer变成了String类型。再经过反序列化,即使已经声明key泛型的Integer,反序列化后内存数据中的key为String并不是Int...

Jackson 泛型序列化

目录 代码实现 代码实现 JSON序列化工具类 调用方法 - End - ﹀ ﹀ ﹀ 梦想是咸鱼 关注一下吧...

jackson序列化和反序列化Json

jackson包提供了java对象与json相互转换的API。 jackson转换机制 Jackson要求java对象是一个POJO对象,即它是一个普通JavaBean对象。此外,如果字段是用private修饰的,则必须有getXXX()方法,否则字段用public修饰。 json常见格式如下 jackson把JavaBean对象的每个字段映射为json的键,json键值由JavaBean的get...

泛型T 反序列化

private <T> List<T> getRecordList(List<String> events, Class<T> tClass) { ArrayList<T> list = new ArrayList<>(); https://stackoverflow.com/questions/18397342/deseri...

Jackson反序列化

jackson介绍         Jackson是一个能够将java对象序列化为JSON字符串,也能够将JSON字符串反序列化为java对象的框架。是基于Java平台的一套数据处理工具,被称为”最好的Java Json解析器”。它可以使我们高效、简便的处理json字符串。 序列化 序列化函数为...

猜你喜欢

Jackson多层泛型深度嵌套导致的反序列化问题

问题描述: 对于一个多层嵌套泛型(深度泛型)的对象进行序列化是容易的,但是反序列化却往往不是很顺利。 我们设计了一个多层泛型嵌套的对象map,对其进行序列化,是没有问题的 我们现在使用反序列化处理 结果抛出了异常 Jackson是不支持多泛型深度嵌套反序列化的,强转后的结果就是默认将AlUsers对象变成了LinkedHashMap,所以在循环的时候强转AlUsers对象就会报错 即使我在每一层都...

Jackson反序列化遇到泛型数据的处理方案

2019独角兽企业重金招聘Python工程师标准>>> Jackson泛型序列化和反序列化问题 基础数据类型序列化和反序列化 } //output: { "id" : 1, "Career_description" : "person description", "birth_name" : &quo...

序列化和反序列化知识汇总

文章目录 概述 对字符串进行序列化 对java对象进行序列化 复写readObject和writeObject 为何复写readObject和writeObject 问题总结 1.序列化之前和反序列化之后的对象可能是同一个对象吗? 2.序列化和反序列化破坏单例模式的解决? 3.实现了Serializable接口的serialVersionUID作用是什么? 概述 如果没有实现Serializabl...

jackson对Exception类型对象的序列化与反序列化

发现问题 今天在调试系统错误通知的时候遇到了一个问题。我们在系统异常时候要通过队列系统发送各种通知到团队内部成员。 因此我写了一个通用接口。接口中有传递Exception对象到队列中,再由队列消费者解析后生成消息发送出去。 这个Exception对象是先通过jackson序列化后再在队列消费端反序列化完成传递的。 但是在测试过程中发现,经过队列传递后的Exception对象丢失了很多信息,甚至连基...