如何将 Java 对象转换为字节数组307


在 Java 中,字节数组(byte[])用于存储二进制数据。有时,我们需要将 Java 对象转换为字节数组,以进行持久化、网络传输或其他目的。本文将介绍几种将 Java 对象转换为字节数组的方法,包括使用序列化、Jackson 库和手动编码。

序列化

序列化是 Java 提供的标准机制,用于将对象转换为字节数组。序列化过程涉及以下步骤:
实施 Serializable 接口。
使用 ObjectOutputStream 类将对象写入字节数组。
使用 ObjectInputStream 类从字节数组中读取对象。

示例代码如下:```java
// 类需要实现 Serializable 接口
public class Person implements Serializable {
private String name;
private int age;
}
// 将 Person 对象转换为字节数组
public byte[] serialize(Person person) throws IOException {
try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos)) {
(person);
return ();
}
}
// 从字节数组中读取 Person 对象
public Person deserialize(byte[] bytes) throws IOException, ClassNotFoundException {
try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bais)) {
return (Person) ();
}
}
```

Jackson 库

Jackson 库提供了强大的 JSON 处理功能,它也可以用来将 Java 对象转换为字节数组。Jackson 库使用 JSON 来表示对象,JSON 是一种基于文本的数据交换格式。

示例代码如下:```java
// 引入 Jackson 依赖项
import ;
// 将 Person 对象转换为 JSON 字节数组
public byte[] serializeWithJackson(Person person) throws IOException {
ObjectMapper mapper = new ObjectMapper();
return (person);
}
// 从 JSON 字节数组中读取 Person 对象
public Person deserializeWithJackson(byte[] bytes) throws IOException {
ObjectMapper mapper = new ObjectMapper();
return (bytes, );
}
```

手动编码

除了序列化和 Jackson 库之外,我们还可以手动将 Java 对象转换为字节数组。这个过程涉及使用位运算符和数据类型转换来逐个字节地构建字节数组。

示例代码如下:```java
// 将 Person 对象转换为字节数组
public byte[] serializeManually(Person person) {
byte[] bytes = new byte[8 + ().length() + 4];
bytes[0] = (byte) (() >> 24);
bytes[1] = (byte) (() >> 16);
bytes[2] = (byte) (() >> 8);
bytes[3] = (byte) (());
byte[] nameBytes = ().getBytes();
(nameBytes, 0, bytes, 8, );
bytes[8 + ] = (byte) (() >> 24);
bytes[8 + + 1] = (byte) (() >> 16);
bytes[8 + + 2] = (byte) (() >> 8);
bytes[8 + + 3] = (byte) (());
return bytes;
}
// 从字节数组中读取 Person 对象
public Person deserializeManually(byte[] bytes) {
int age = (bytes[0]

2024-10-24


上一篇:如何判断 Java 中给定值是否为数组

下一篇:Java 中向网络服务器发送数据的全面指南