java 对象序列化中替代方案主要有 json(如 jackson、gson)、protobuf、kryo 以及 hessian。具体做法是引入对应库的依赖,将对象序列化为字节数组或字符串进行传输或存储,反序列化时再还原为对象。

JSON 序列化方案如何实现
使用 Jackson 库可以将 Java 对象直接转换为 JSON 字符串或字节流。通过 ObjectMapper 实例调用 writeValueAsString() 或 writeValueAsBytes() 方法即可完成序列化,反序列化则使用 readValue() 方法。这种方式可读性强,兼容性好,是目前 Web 开发中最主流的序列化方式。

import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonExample {
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
User user = new User("Alice", 30);
// 序列化:对象 -> JSON 字符串
String json = mapper.writeValueAsString(user);
System.out.println("Serialized: " + json);
// 反序列化:JSON 字符串 -> 对象
User deserializedUser = mapper.readValue(json, User.class);
System.out.println("Deserialized: " + deserializedUser.getName());
}
}
class User {
private String name;
private int age;
public User() {}
public User(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() { return name; }
public void setName(String name) { this.name = name; }
}
Kryo 高性能序列化方案如何工作
Kryo 是一个快速高效的 Java 对象序列化框架,专为二进制格式设计。它通过 Kryo 和 Output/Input 类配合使用,实现对象到字节数组的快速转换。相比 JSON,Kryo 序列化后的体积更小,速度更快,适合对性能要求较高的内部系统通信场景。

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import java.nio.ByteBuffer;
public class KryoExample {
public static void main(String[] args) {
Kryo kryo = new Kryo();
kryo.register(User.class);
User user = new User("Bob", 25);
// 序列化:对象 -> 字节数组
Output output = new Output(new ByteBuffer(1024));
kryo.writeObject(output, user);
byte[] bytes = output.toBytes();
System.out.println("Serialized length: " + bytes.length);
// 反序列化:字节数组 -> 对象
Input input = new Input(bytes);
User deserializedUser = kryo.readObject(input, User.class);
System.out.println("Deserialized: " + deserializedUser.getName());
}
}
Protobuf 跨语言序列化如何处理字段类型
Protocol Buffers (Protobuf) 是一种语言无关、平台无关的序列化机制。它需要预先定义 .proto 文件来指定消息结构,然后生成各语言的代码。在 Java 中,生成的类提供 toByteArray() 和 parseFrom() 方法进行序列化和反序列化。Protobuf 支持多种基本类型和复合类型,具有严格的类型检查和高效的二进制编码,特别适合跨语言微服务通信。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











