Java Serializable Object to Byte Array

后端 未结 12 1315
春和景丽
春和景丽 2020-11-22 03:12

Let\'s say I have a serializable class AppMessage.

I would like to transmit it as byte[] over sockets to another machine where it is rebuil

相关标签:
12条回答
  • 2020-11-22 03:31

    This is just an optimized code form of the accepted answer in case anyone wants to use this in production :

        public static void byteArrayOps() throws IOException, ClassNotFoundException{
    
        String str="123";
         byte[] yourBytes = null;
    
        // Convert to byte[]
    
        try(ByteArrayOutputStream bos = new ByteArrayOutputStream();
                ObjectOutputStream out =  new ObjectOutputStream(bos);) {
    
    
          out.writeObject(str);
          out.flush();
          yourBytes = bos.toByteArray();
    
        } finally {
    
        }
    
        // convert back to Object
    
        try(ByteArrayInputStream bis = new ByteArrayInputStream(yourBytes);
                ObjectInput in = new ObjectInputStream(bis);) {
    
          Object o = in.readObject(); 
    
        } finally {
    
        }
    
    
    
    
    }
    
    0 讨论(0)
  • 2020-11-22 03:33

    In case you want a nice no dependencies copy-paste solution. Grab the code below.

    Example

    MyObject myObject = ...
    
    byte[] bytes = SerializeUtils.serialize(myObject);
    myObject = SerializeUtils.deserialize(bytes);
    

    Source

    import java.io.*;
    
    public class SerializeUtils {
    
        public static byte[] serialize(Serializable value) throws IOException {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
    
            try(ObjectOutputStream outputStream = new ObjectOutputStream(out)) {
                outputStream.writeObject(value);
            }
    
            return out.toByteArray();
        }
    
        public static <T extends Serializable> T deserialize(byte[] data) throws IOException, ClassNotFoundException {
            try(ByteArrayInputStream bis = new ByteArrayInputStream(data)) {
                //noinspection unchecked
                return (T) new ObjectInputStream(bis).readObject();
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-22 03:36

    Spring Framework org.springframework.util.SerializationUtils

    byte[] data = SerializationUtils.serialize(obj);
    
    0 讨论(0)
  • 2020-11-22 03:37

    I would like to transmit it as byte[] over sockets to another machine

    // When you connect
    ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
    // When you want to send it
    oos.writeObject(appMessage);
    

    where it is rebuilt from the bytes received.

    // When you connect
    ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
    // When you want to receive it
    AppMessage appMessage = (AppMessage)ois.readObject();
    
    0 讨论(0)
  • 2020-11-22 03:44

    code example with java 8+:

    public class Person implements Serializable {
    
    private String lastName;
    private String firstName;
    
    public Person() {
    }
    
    public Person(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }
    
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    
    public String getFirstName() {
        return firstName;
    }
    
    public String getLastName() {
        return lastName;
    }
    
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    
    @Override
    public String toString() {
        return "firstName: " + firstName + ", lastName: " + lastName;
    }
    }
    
    
    public interface PersonMarshaller {
    default Person fromStream(InputStream inputStream) {
        try (ObjectInputStream objectInputStream = new ObjectInputStream(inputStream)) {
            Person person= (Person) objectInputStream.readObject();
            return person;
        } catch (IOException | ClassNotFoundException e) {
            System.err.println(e.getMessage());
            return null;
        }
    }
    
    default OutputStream toStream(Person person) {
        try (OutputStream outputStream = new ByteArrayOutputStream()) {
            ObjectOutput objectOutput = new ObjectOutputStream(outputStream);
            objectOutput.writeObject(person);
            objectOutput.flush();
            return outputStream;
        } catch (IOException e) {
            System.err.println(e.getMessage());
            return null;
        }
    
    }
    
    }
    
    0 讨论(0)
  • 2020-11-22 03:46

    Another interesting method is from com.fasterxml.jackson.databind.ObjectMapper

    byte[] data = new ObjectMapper().writeValueAsBytes(JAVA_OBJECT_HERE)

    Maven Dependency

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
    </dependency>
    
    0 讨论(0)
提交回复
热议问题