|
| 1 | +``` |
| 2 | +title: 序列化和反序列化 |
| 3 | +date: 2025/12/15 |
| 4 | +categories: |
| 5 | + - 杂谈 |
| 6 | +tags: |
| 7 | + - 序列化 |
| 8 | +``` |
| 9 | +# 序列化和反序列化 |
| 10 | +## 序列化 |
| 11 | +将对象转换为可存储或可传输的字节流或其他数据格式的**过程**。 |
| 12 | +依赖FastJSON的序列化(序列化为JSON) |
| 13 | +```java |
| 14 | +public static void main(String[] args) throws Exception { |
| 15 | + User user = new User(); |
| 16 | + user.setAge(18); |
| 17 | + user.setUserName("张三"); |
| 18 | + String jsonString = JSONObject.toJSONString(user); |
| 19 | + File file = new File("user.json"); |
| 20 | + Files.write(file.toPath(), jsonString.getBytes(StandardCharsets.UTF_8)); |
| 21 | + System.out.println(file.length()); |
| 22 | + } |
| 23 | +``` |
| 24 | +将对象序列化为字节数组 |
| 25 | +```java |
| 26 | + private static byte[] serialize(User user) { |
| 27 | + String name = user.getUserName(); |
| 28 | + byte[] nameBytes = name.getBytes(StandardCharsets.UTF_8); |
| 29 | + ByteBuffer buffer = ByteBuffer.allocate(nameBytes.length + Integer.BYTES); |
| 30 | + buffer.putInt(user.getAge()); |
| 31 | + buffer.put(nameBytes); |
| 32 | + return buffer.array(); |
| 33 | + } |
| 34 | + |
| 35 | +``` |
| 36 | +对象实现serializable的序列化 |
| 37 | +```java |
| 38 | + private static byte[] serialize(User user) throws IOException { |
| 39 | + ByteArrayOutputStream baos = new ByteArrayOutputStream(); |
| 40 | + ObjectOutputStream oob = new ObjectOutputStream(baos); |
| 41 | + oob.writeObject(user); |
| 42 | + return baos.toByteArray(); |
| 43 | + } |
| 44 | +``` |
| 45 | +## 反序列化 |
| 46 | +将字节流或其他格式的数据还原为对象的过程 |
| 47 | + |
| 48 | +依赖FastJSON的反序列化 |
| 49 | +```java |
| 50 | +public static void main(String[] args) throws Exception { |
| 51 | + File file = new File("user.json"); |
| 52 | + byte[] bytes = Files.readAllBytes(file.toPath()); |
| 53 | + User user = JSONObject.parseObject(new String(bytes, StandardCharsets.UTF_8), User.class); |
| 54 | + System.out.println(user); |
| 55 | + } |
| 56 | +``` |
| 57 | +将字节数组反序列化为对象 |
| 58 | +```java |
| 59 | + private static User deserialize(byte[] bytes){ |
| 60 | + ByteBuffer buffer = ByteBuffer.wrap(bytes); |
| 61 | + int age = buffer.getInt(); |
| 62 | + byte[] nameBytes = new byte[buffer.remaining()]; |
| 63 | + buffer.get(nameBytes); |
| 64 | + User user = new User(); |
| 65 | + user.setAge(age); |
| 66 | + user.setUserName(new String(nameBytes, StandardCharsets.UTF_8)); |
| 67 | + return user; |
| 68 | + } |
| 69 | +``` |
| 70 | +对象实现serializable的反序列化 |
| 71 | +```java |
| 72 | +private static User deserialize(byte[] bytes) throws Exception { |
| 73 | + ByteArrayInputStream bais = new ByteArrayInputStream(bytes); |
| 74 | + ObjectInputStream objectInputStream = new ObjectInputStream(bais); |
| 75 | + return (User) objectInputStream.readObject(); |
| 76 | + } |
| 77 | +``` |
0 commit comments