无法序列化将 java POJO class 转换为字节数组

Unable to serialize convert java POJO class into a byte array

如何将 java POJO class 转换为字节数组,因为我想将对象保存到 S3 中的 gz 文件中

我得到这个异常Caused by: java.io.NotSerializableException

    public byte[] compressData(User user) throws IOException {

            byte[] data;
            try(ByteArrayOutputStream byteStream = new ByteArrayOutputStream();) {
                try (GZIPOutputStream objectOutputStream = new GZIPOutputStream(byteStream);) {
                    try (ObjectOutputStream zipStream = new ObjectOutputStream(objectOutputStream);) {
                        zipStream.writeObject(user);
                    }
                    data = byteStream.toByteArray();
                } catch (Exception e) {
                    throw new IOException(e);
                }
            }
            return data;
}

您可以使用 ApacheCommonslang 依赖项中的 SerializationUtils.java

  1. 用于连载

    byte[] data = SerializationUtils.serialize(**POJO_Object_Name**);
    
  2. 反序列化:

    POJO_Class_Name **POJO_Object_Name**  = SerializationUtils.deserialize(data)
    
private final Type userType = new TypeToken<User>() {}.getType();

private final Gson = new Gson();

compressData(gson.toJson(user,userType));

 public static byte[] compressData(String user) throws IOException {

        byte[] data;
        try(ByteArrayOutputStream byteStream = new ByteArrayOutputStream();){
            try(GZIPOutputStream zipStream = new GZIPOutputStream(byteStream);){
                zipStream.write(data.getBytes(StandardCharsets.UTF_8));
            }
            data = byteStream.toByteArray();
        } catch(Exception e) {
            throw new IOException("Error while compressing the User record ", e);
        }
        return data;
    }