序列化和反序列化

序列化

将对象转换为可存储或可传输的字节流或其他数据格式的过程
依赖FastJSON的序列化(序列化为JSON)

public static void main(String[] args) throws Exception {
        User user = new User();
        user.setAge(18);
        user.setUserName("张三");
        String jsonString = JSONObject.toJSONString(user);
        File file = new File("user.json");
        Files.write(file.toPath(), jsonString.getBytes(StandardCharsets.UTF_8));
        System.out.println(file.length());
    }

将对象序列化为字节数组

    private static byte[] serialize(User user) {
        String name = user.getUserName();
        byte[] nameBytes = name.getBytes(StandardCharsets.UTF_8);
        ByteBuffer buffer = ByteBuffer.allocate(nameBytes.length + Integer.BYTES);
        buffer.putInt(user.getAge());
        buffer.put(nameBytes);
        return buffer.array();
    }
   

对象实现serializable的序列化

 private static byte[] serialize(User user) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oob = new ObjectOutputStream(baos);
        oob.writeObject(user);
        return baos.toByteArray();
    }

反序列化

将字节流或其他格式的数据还原为对象的过程

依赖FastJSON的反序列化

public static void main(String[] args) throws Exception {
        File file = new File("user.json");
        byte[] bytes = Files.readAllBytes(file.toPath());
        User user = JSONObject.parseObject(new String(bytes, StandardCharsets.UTF_8), User.class);
        System.out.println(user);
    }

将字节数组反序列化为对象

 private static User deserialize(byte[] bytes){
        ByteBuffer buffer = ByteBuffer.wrap(bytes);
        int age = buffer.getInt();
        byte[] nameBytes = new byte[buffer.remaining()];
        buffer.get(nameBytes);
        User user = new User();
        user.setAge(age);
        user.setUserName(new String(nameBytes, StandardCharsets.UTF_8));
        return user;
    }

对象实现serializable的反序列化

private static User deserialize(byte[] bytes) throws Exception {
        ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
        ObjectInputStream objectInputStream = new ObjectInputStream(bais);
        return (User) objectInputStream.readObject();
    }