复习盘点-Java序列化方式(1)JSON序列化(温故知新-泛型)(jdk8-LocalDate序列化)

Java中的RPC(远程服务调用)可以通过序列化的方式进行。

JDK英文文档,墙裂不推荐看中文!!!

1. Jackson 进行JSON的解析和序列化

1.1 Jackson的API

ObjectMapper的API文档

1 需要注意的是:

  • ObjectMapperJSON操作的核心,Jackson的JSON操作都是在ObjectMapper中实现的。
  • ObjectMapper有多个JSON序列化的方法,可以把JSON串保存在FileOutputStream等不同的介质中。

2 Jackson的API:`

  • writeValue(File resultFile, Object value)可以用于所有Java值的序列化,将JSON输出到File中。

  • writeValue(OutputStream out, Object value) 可以用于所有Java对象的序列化,并将JSON串保存到流中。注意,此方法不会显示的关闭流。

  • writeValueAsString(Object value)可以用于任何Java对象的序列化方式,并输出字符串。等效于writeValue(Writer,Object) 并构造String,但是效率更高。

  • writeValueAsBytes(Object value)可用于任何Java对象的序列化方式,并输出byte[]数组。等效于writeValue(Writer,Object) 并得到byte[]数组,注意数组的编码是UTF-8

  • T readValue(String content, Class valueType)注意,我们在传入Class对象,注意一般是传入Class,因为Class类中并不使用泛型对象,但是此处使用泛型对象,因为我们的返回值就是T,避免了类型强转。温故知新——泛型实践篇

3. Jackson提供的注解
Jackson提供了一系列的注解,方便对JSON序列化和反序列化进行控制,下面介绍一些常用的注解:

  • JsonIgnore 此注解用于属性上,作用是Json操作时,忽略该属性。
  • JsonFormat 此注解用于属性上, 作用是把Date类型转化成为想要的格式。
  • JsonProperty 此注解用于属性上,作用是把改属性的名称序列化成另一个名称。
  • JsonSerialize 此注解用于属性上,作用是指定属性序列化的类型。
  • JsonDeserialize 此注解用于属性上,作用是指定属性反序列化的类型。

1.2 Jackson源码分析

1.2.1 源码

1. 引入MAVEN依赖:

     
      
            com.fasterxml.jackson.core
            jackson-databind
            2.9.4
        
      
      
            com.fasterxml.jackson.datatype
            jackson-datatype-jsr310
      

2. 实体类

public class User implements Serializable {

    private String name;
    private List sports;
    //序列化格式
    //@JsonSerialize(using = LocalDateSerializer.class)
    //反序列化格式
    //@JsonDeserialize(using = LocalDateDeserializer.class)
    //Json格式
    //@JsonFormat(pattern = "yyyy-MM-dd")
    private LocalDate date;
   //节省篇幅,省略get/set方法
}

3. 测试类:

public static void main(String[] args) {
        //创建用户对象
        User user = new User();
        user.setName("小胖");
        List sports = new ArrayList<>();
        sports.add("足球");
        sports.add("游泳");
        user.setSports(sports);
        user.setDate(LocalDate.now());
        //创建对象
        //Json序列化和反序列化
        ObjectMapper mapper = new ObjectMapper();
//        mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
//        mapper.registerModule(new JavaTimeModule());
        //User转化为Json
        try {
            //对象转化为Json数据
            String s = mapper.writeValueAsString(user);
            System.out.println("s:" + s);
            //Json转化为对象
            User user1 = mapper.readValue(s, User.class);
            System.out.println(user1.toString());
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

1.2.2 源码分析

首先注意的是JDK1.8中时间类,采用了一套新的API。

在这里我们采用是LocalDate类,若是User类中,没有使用注解,那么序列化结果为:

{
    "name": "小胖",
    "sports": ["足球", "游泳"],
    "date": {
        "year": 2019,
        "month": "MARCH",
        "chronology": {
            "id": "ISO",
            "calendarType": "iso8601"
        },
        "dayOfMonth": 27,
        "dayOfWeek": "WEDNESDAY",
        "dayOfYear": 86,
        "era": "CE",
        "monthValue": 3,
        "leapYear": false
    }
}

显然,这不是我们预期的Json串。并且,我们在反序列化过程中,会出现异常:

com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of java.time.LocalDate (no Creators, like default construct, exist):
cannot deserialize from Object value (no delegate- or property-based Creator)
at [Source: (String)"{"name":"小胖","sports":["足球","游泳"],"date":{"year":2019,"month":"MARCH","chronology":{"id":"ISO","calendarType":"iso8601"},"dayOfMonth":27,"dayOfWeek":"WEDNESDAY","dayOfYear":86,"era":"CE","monthValue":3,"leapYear":false}}"; line: 1, column: 43] (through reference chain: com.JsonSerializer.User["date"])

大概意思:就是LocalDate的没有参数是Object的构造函数。不能实例化对象。


华丽的分割线SpringBoot的处理

SpringBoot的解决方案:

  1. 首先在MAVEN 中加入ckson-datatype-jsr310依赖。

  com.fasterxml.jackson.datatype
  jackson-datatype-jsr310

  1. 配置Configuration中的ObjectMapper
@Bean
public ObjectMapper serializingObjectMapper() {
  ObjectMapper objectMapper = new ObjectMapper();
  objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
  objectMapper.registerModule(new JavaTimeModule());
  return objectMapper;
}

Java bean的解决方案:
Java Bean中使用注解,就可以进行反序列化和序列化。

    //序列化格式
    @JsonSerialize(using = LocalDateSerializer.class)
    //反序列化格式
    @JsonDeserialize(using = LocalDateDeserializer.class)
    //Json格式
    @JsonFormat(pattern = "yyyy-MM-dd")
    private LocalDate date;

执行结果:

复习盘点-Java序列化方式(1)JSON序列化(温故知新-泛型)(jdk8-LocalDate序列化)_第1张图片
Jackson序列化和反序列化的结果

2. FastJson 序列化

2.1 FastJson的API

FastJson是性能极好的JSON解析器和生成器。

1. FastJson的优点:

  • 速度快:超越其他任何java json parser
  • 功能强大:支持Java BeanCollectionMap、日期、枚举、支持泛型和自省。
  • 零依赖:只依赖于JDK

2. FastJson的主要类:

  1. JSON:FastJson解析器,用于JSON格式字符串与JSON对象以及javaBean之间转换。
  2. JSONObject:FastJson提供的json对象。
  3. JSONArray:FastJson提供的json数组对象。

2.2 FastJson的准备工作

1. FastJson的MAVEN依赖:

        
            com.alibaba
            fastjson
            1.2.2
        

2. JSON准备:

    private static final String OBJ_JSON = "{\"studentName\":\"lily\",\"studentAge\":12}";
    private static final String ARR_JSON = "[{\"studentName\":\"lily\",\"studentAge\":12},{\"studentName\":\"lucy\",\"studentAge\":15}]";
    private static final String COMPLEX_JSON = "{\"teacherName\":\"crystall\",\"teacherAge\":27,\"course\":{\"courseName\":\"english\",\"code\":1270},\"students\":[{\"studentName\":\"lily\",\"studentAge\":12},{\"studentName\":\"lucy\",\"studentAge\":15}]}";

ARR_JSON格式:

[{
    "studentName": "lily",
    "studentAge": 12
}, {
    "studentName": "lucy",
    "studentAge": 15
}]

COMPLEX_JSON格式:

{
    "teacherName": "crystall",
    "teacherAge": 27,
    "course": {
        "courseName": "english",
        "code": 1270
    },
    "students": [{
        "studentName": "lily",
        "studentAge": 12
    }, {
        "studentName": "lucy",
        "studentAge": 15
    }]
}

2.3 JSON字符串和JSONObject或JSONArray之间的转换

我们日常操作是:JSON字符串JavaBean对象之间的转换。但是为什么存在JSONObject或者JSONArray对象呢?因为我们不想为每一个JSON字符串都创建一个Bean对象,但是我们还是想像对象一样操作JSON串时。就可这样操作

2.3.1 JSON字符串和JSONObject之间的转换

1 JSON到JSONObject的转换;
JSONObject object = JSONObject.parseObject(OBJ_JSON);

  1. JSONObject到JSON的转换;
    String toJSONString = JSONObject.toJSONString(object);
复习盘点-Java序列化方式(1)JSON序列化(温故知新-泛型)(jdk8-LocalDate序列化)_第2张图片
JSONObject和JSON的转换

2.3.2 数组对象型——JSON和JSONArray转换

  1. JSON到JSONArray的转换;
    JSONArray jsonArray = JSONArray.parseArray(ARR_JSON);
    需要注意的是JSONArray实现了List接口。
  2. JSONArray到JSON的转换;
    String string = jsonArray.toJSONString();
  3. 2.3.3 如何操作JSONObject对象

    1. 获取JSONObject里面的JSONObject对象;
      jsonObject.getJSONObject("course");
    2. 获取JSONObject里面的JSONArray对象;
      jsonObject.getJSONArray("students");
    3. 获取JSONObject里面的String或基本数据类型;
      jsonObject.getXXX("students");
      public static void main(String[] args) {
            JSONObject jsonObject = JSONObject.parseObject(COMPLEX_JSON);
            //获取JSON中的参数
            jsonObject.getString("teacherName");
            //获取JSON中的对象
            jsonObject.getJSONObject("course");
            //获取JSON中数组
            jsonObject.getJSONArray("students");
            //JSON转换为Object
            String jsonString = jsonObject.toJSONString();
            System.out.println("序列化后的对象"+jsonString);
        }
    

    2.4 JSON字符串和JavaBean之间的转换

    JSON和JavaBean之间的转化,其实是将转化Bean的class对象传入即可。

    2.4.1 JSON转化为Object(TypeReference方式)

    FastJson中提供了一个可用来处理泛型反序列化的类TypeRefernce

    2.4.1.1 TypeRefrence进行反序列化

    通过设置new TypeReference>() {};,JSON字符串反序列化成Teacher对象会保留泛型

    使用方式:github的使用文档

    1. 通过TypeReference处理泛型对象

         Teacher teacher = JSONObject.parseObject(COMPLEX_JSON, new TypeReference>() {
            });
    

    2. 使用getType()可以获取更好的性能。

            Type type = new TypeReference>() {
            }.getType();
            Teacher teacher = JSONObject.parseObject(COMPLEX_JSON, type);
    

    2.4.1.2 TypeRefrence源码分析

    1. TypeRefrence部分源码分析:

    public class TypeReference {
        static ConcurrentMap classTypeCache = new ConcurrentHashMap(16, 0.75F, 1);
        protected final Type type;
        public static final Type LIST_STRING = (new TypeReference>() {
        }).getType();
    
        protected TypeReference() {
            Type superClass = this.getClass().getGenericSuperclass();
            Type type = ((ParameterizedType)superClass).getActualTypeArguments()[0];
            Type cachedType = (Type)classTypeCache.get(type);
            if (cachedType == null) {
                classTypeCache.putIfAbsent(type, type);
                cachedType = (Type)classTypeCache.get(type);
            }
    
            this.type = cachedType;
        }
    
        public Type getType() {
            return this.type;
        }
    

    为什么这里的构造方法要是protected的,即我们无法直接创建该对象,只能使用匿名类创建子类对象。

    getGenericSuperclass()的API方法

    public Type getGenericSuperclass();

    • Returns the Type representing the direct superclass of the entity (class, interface, primitive type or void) represented by this Class.
    • If the superclass is a parameterized type, the Type object returned must accurately reflect the actual type parameters used in the source code.

    返回Class对象(类,接口,基本数据类型,void)的直接父类的Type类型。
    如果父类是parameterized [pə'ræmɪtəraɪzd]类型(也可以理解为父类是泛型对象),那么返回的参数类型是父类的泛型类型。

    基本原理:

    • 类型擦除是擦除的方法中Code字节码,但是会把泛型类型保存在Signature中,不能通过反射直接获取,但是可以通过子类获取父类的泛型类型。

    • 类型擦除不会将元数据(即类结构)上的泛型擦除,还是可以通过反射直接获取。复习盘点——泛型擦除。

    • 可以通过匿名内部类的方式获取子类,在这里,推荐使用protected构造方法,创建匿名类。复习盘点——内部类


    2.4.2 JSON转化为Object(Class方式)

    不保留泛型的反序列化。

    使用public static T parseObject(String text, Class clazz)方法,边可完成JSON的反序列化。

    1. 特殊JSON反序列化

    需要注意的是,若是text为null的情况下,最后反序列化的结构也是为null

     public static void main(String[] args) {
            UserPO userPO = JSON.parseObject(null, UserPO.class);
            System.out.println(userPO);    //若是null,反序列化对象也是null
            UserPO userPO1 = JSON.parseObject("", UserPO.class);
            System.out.println(userPO1);  //若是空串,抛出异常
            UserPO userPO2 = JSON.parseObject("{}", UserPO.class);
            System.out.println(userPO2);  //若是空JSON,返回空对象
        }
    

    2. 泛型丢失

    Teacher teacher = JSONObject.parseObject(COMPLEX_JSON, Teacher.class);
    

    我们可以看到,因为返回值需要泛型类型T所以我们采用的是Class,防止返回Object对象,让用户强转。但需要注意:这种方式在反序列化的时候,会丢失泛型类型。

    2.4.3 JSON转化为Object集合对象

    方式一:TypeReference

    //获取数组对象的List的Type
    Type type = new TypeReference>() {
    }.getType();
    
    List list = JSONObject.parseObject(ARR_JSON, type);
    System.out.println(list);
    

    方式二:使用parseArray

        List students = JSONObject.parseArray(ARR_JSON, Student.class);
    

    2.4.4 Object转化为(自定义格式)的JSON

    我们通过:fastjson如何json数组串转换为Object[]时如何指定各个数据项的数据类型引出fastjson SerializerFeature对象

    我们可以通过这个API,完成Bean对象转换成String类型。
    String toJSONString(Object object, SerializerFeature... features)

    复习盘点-Java序列化方式(1)JSON序列化(温故知新-泛型)(jdk8-LocalDate序列化)_第3张图片
    SerializerFeature模式的使用
      Student stu = new Student();
            stu.setStudentAge(null);
            stu.setStudentName("黎明");
            String toJSONString = JSONObject.toJSONString(stu,
                    SerializerFeature.PrettyFormat,
                    SerializerFeature.WriteNullStringAsEmpty,  //如果字符串是空,那么返回"",而非不返回
                    SerializerFeature.WriteNullNumberAsZero,  //如果字符串是空,那么返回0,而不是不返回、
                    SerializerFeature.WriteClassName,     //序列化时写入类型信息,反序列化时用到
                    SerializerFeature.DisableCircularReferenceDetect); //消除对同一对象循环引用问题。
            System.out.println(toJSONString);
    
    复习盘点-Java序列化方式(1)JSON序列化(温故知新-泛型)(jdk8-LocalDate序列化)_第4张图片
    SerializerFeature序列化方式

    2.5 JSON转化为Object到底采用哪种方式

    在项目中,一般都是使用JSON进行数据的传输。那么通常采用Class方式还是TypeRefrence方式进行反序列化呢?

    1. JSON转化为简单对象

    若是对象的属性只是简单数据类型(基本数据类型,或者String类型)那么可以使用Class方式转化为Object对象。

    JSON.parseObject(dataInfo.getData(), Order.class);
    

    2. JSON转化为复杂对象

    若是一个对象里面的属性依旧是一个对象,那么我们就可以使用TypeRefrence进行转换。

    public class ApiResponseVo {
        private String subCode;
        private String subMsg;
        private String count;
        private List list;
        //省略 getter、setter方法
    }
    

    我们在将JSON转换为对象的时候,就可以保留List的泛型。即:

    ApiResponseVo apiResponseVo=
    JSON.parseObject(dataInfo.getData(), new TypeReference>(){});
    

    参考文章:
    Java下利用Jackson进行JSON解析和序列化

    使用FastJson处理JSON数据

    fastjson如何json数组串转换为Object[]时如何指定各个数据项的数据类型

    你可能感兴趣的:(复习盘点-Java序列化方式(1)JSON序列化(温故知新-泛型)(jdk8-LocalDate序列化))