1,什么是序列化?
Java序列化是指把Java对象转换为字节序列的过程,而Java反序列化是指把字节序列恢复为Java对象的过程。
2,序列化的使用场景
-
永久性保存对象,保存对的字节序列到本地文件或者数据库中;
-
通过序列化以字节流的形式对象在网络中进行传递和接收;
-
通过序列化在进程间传递对象;
3,java 的对象流序列化
package com.demo.base.serializable;
import java.io.*;
/**
* 序列化
* 1,Serializable 普通序列化
* 2,Externalizable 自定义序列化
* */
public class SerializableDemo {
public static class Person implements Serializable {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
public static void main(String[] args) throws IOException {
//序列化
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("C:\\Users\\GaoXin\\Desktop\\test.txt"));
Person person = new Person("张三", 14);
objectOutputStream.writeObject(person);
//反序列化
ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("C:\\Users\\GaoXin\\Desktop\\test.txt"));
try {
Person p = (Person) objectInputStream.readObject();
System.out.println(p);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
4,Fastjson 序列化
public static void fastJsonSerializable(){
Duck duck = new Duck("张三", 14);
Person yq = new Person("yq");
yq.setAnimal(duck);
String s = JSON.toJSONString(yq);
Person person = JSON.parseObject(s, Person.class);
System.out.println(person);
}
5,Jackson 序列化
Jackson 序列化是通过实体类的无参构造方法处理的,所以当有以下情形时反序列化会有问题
1)实体类某个字段的引用是个接口
2)实体类没有无参构造
解决方法:自定义反序列化
实体类:Person 对象持有一个 Animal 接口类型的属性,这时候如果我们使用 ObjectMapper 反序列化会报错
@Data
@JsonDeserialize(using = PersonDeserialize.class)
public class Person implements Serializable {
private String name;
//类上有自定义的,这个就不起作用力
//@JsonDeserialize(using = AnimalDeserialize.class)
private Animal animal;
public Person(){}
public Person(String name){
this.name = name;
}
}
public interface Animal extends Serializable {
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Duck implements Animal {
private String name;
private Integer age;
}
自定义的 Person 反序列化实现
public class PersonDeserialize extends JsonDeserializer<Person> {
@Override
public Person deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException, JacksonException {
JsonNode json = jsonParser.getCodec().readTree(jsonParser);
String name = json.get("name").asText();
Person person = new Person(name);
ObjectMapper om = new ObjectMapper();
Animal animal = om.readValue(json.get("animal").toString(), Duck.class);
person.setAnimal(animal);
return person;
}
}
测试
public static void jacksonSerializable() throws JsonProcessingException {
Duck duck = new Duck("张三", 14);
Person yq = new Person("yq");
yq.setAnimal(duck);
JsonMapper jsonMapper = new JsonMapper();
String s = jsonMapper.writeValueAsString(yq);
ObjectMapper objectMapper = new ObjectMapper();
System.out.println( objectMapper.readValue(s, Person.class));
}