Java可序列化对象到字节数组

时间:2010-05-14 18:31:20

标签: java object serialization

假设我有一个可序列化的类AppMessage

我想将它作为byte[]通过套接字传输到另一台机器,在那里从接收的字节重建它。

我怎么能实现这个目标?

11 个答案:

答案 0 :(得分:384)

准备要发送的字节:

ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput out = null;
try {
  out = new ObjectOutputStream(bos);   
  out.writeObject(yourObject);
  out.flush();
  byte[] yourBytes = bos.toByteArray();
  ...
} finally {
  try {
    bos.close();
  } catch (IOException ex) {
    // ignore close exception
  }
}

从字节创建对象:

ByteArrayInputStream bis = new ByteArrayInputStream(yourBytes);
ObjectInput in = null;
try {
  in = new ObjectInputStream(bis);
  Object o = in.readObject(); 
  ...
} finally {
  try {
    if (in != null) {
      in.close();
    }
  } catch (IOException ex) {
    // ignore close exception
  }
}

答案 1 :(得分:281)

最好的方法是使用Apache Commons Lang中的SerializationUtils

序列化:

byte[] data = SerializationUtils.serialize(yourObject);

要反序列化:

YourObject yourObject = SerializationUtils.deserialize(data)

如前所述,这需要Commons Lang库。它可以使用Gradle导入:

compile 'org.apache.commons:commons-lang3:3.5'

的Maven:

<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.5</version>
</dependency>

Jar file

提及here

的更多方法

或者,可以导入整个集合。请参阅this link

答案 2 :(得分:77)

如果您使用Java&gt; = 7,则可以使用{{3}}改进已接受的解决方案:

private byte[] convertToBytes(Object object) throws IOException {
    try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
         ObjectOutput out = new ObjectOutputStream(bos)) {
        out.writeObject(object);
        return bos.toByteArray();
    } 
}

反过来说:

private Object convertFromBytes(byte[] bytes) throws IOException, ClassNotFoundException {
    try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
         ObjectInput in = new ObjectInputStream(bis)) {
        return in.readObject();
    } 
}

答案 3 :(得分:5)

可以通过 SerializationUtils ,通过序列化&amp;反序列化方法由ApacheUtils将对象转换为byte [],反之亦然,如@uris answer中所述。

通过序列化将对象转换为byte []:

byte[] data = SerializationUtils.serialize(object);

通过反序列化::

将byte []转换为object
Object object = (Object) SerializationUtils.deserialize(byte[] data)

点击Download org-apache-commons-lang.jar

的链接

点击:

整合.jar文件

FileName - &gt; 打开Medule设置 - &gt; 选择您的模块 - &gt; 依赖关系 - &gt; 添加Jar文件,您就完成了。

希望这会有所帮助

答案 4 :(得分:2)

我还建议使用SerializationUtils工具。我想对@Abilash做出错误的评论。 SerializationUtils.serialize()方法限制为1024字节,这与此处的另一个答案相反。

public static byte[] serialize(Object object) {
    if (object == null) {
        return null;
    }
    ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
    try {
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(object);
        oos.flush();
    }
    catch (IOException ex) {
        throw new IllegalArgumentException("Failed to serialize object of type: " + object.getClass(), ex);
    }
    return baos.toByteArray();
}

乍一看,您可能认为new ByteArrayOutputStream(1024)只允许固定大小。但是如果你仔细查看ByteArrayOutputStream,你会发现如果有必要,流会增长:

  

此类实现数据所在的输出流   写入字节数组。缓冲区自动增长为数据   是写的。   可以使用toByteArray()和\ n检索数据   toString()

答案 5 :(得分:1)

  

我想将它作为byte []通过套接字传输到另一台机器

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

从收到的字节重建它。

// When you connect
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
// When you want to receive it
AppMessage appMessage = (AppMessage)ois.readObject();

答案 6 :(得分:1)

另一种有趣的方法来自@daily /etc/init.d/elasticsearch restart

com.fasterxml.jackson.databind.ObjectMapper

Maven依赖

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

答案 7 :(得分:1)

如果您想要一个不错的无依赖项复制粘贴解决方案。抓取下面的代码。

示例

MyObject myObject = ...

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

来源

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

答案 8 :(得分:0)

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

}

}

答案 9 :(得分:0)

Spring框架studentdoc_setting_index_mapping_type_overlayadjacency.json { "index": { "mapping": { "total_fields": { "limit": "100000" } } } } @Setting(settingPath = "studentdoc_setting_index_mapping_type_overlayadjacency.json") public class StudentDoc { }

org.springframework.util.SerializationUtils

答案 10 :(得分:0)

这只是已接受答案的优化代码形式,以防有人在生产中使用它:

    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 {

    }




}