简体   繁体   中英

Unable to serialize convert java POJO class into a byte array

How to convert java POJO class into a byte array as I wanted to save the object into a gz file in S3

I get this exception 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;
}

you can use SerializationUtils.java from Apache Commonslang dependency.

  1. For serialization

    byte[] data = SerializationUtils.serialize(**POJO_Object_Name**);
  2. for deserialize:

     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;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM