How to convert Object to byte[] and the reverse?

Asked

Viewed 305 times

2

I need to send a file over an udp connection to a college paper. I created a package class that contains the header and part of the file to be sent. I did the following method to convert the object to byte[]:

 public static byte[] objectToByte(Object obj) throws IOException {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
    objectOutputStream.writeObject(obj);
    objectOutputStream.flush();
    objectOutputStream.close();
    byteArrayOutputStream.close();
    return byteArrayOutputStream.toByteArray();

}

And I created the following to convert back to Object:

public static Object byteToObject(byte[] bytes) throws IOException, ClassNotFoundException {
    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
    ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
    Object object = objectInputStream.readObject();
    objectInputStream.close();
    return object;
}

I tested and the methods without sending by the connection and worked, but when sending by the datagram and will be done the conversion back to Object gives the error: java.io.Streamcorruptedexception: invalid type code: 00 Along those lines:

Object object = objectInputStream.readObject();

Does anyone know what it can be?

Customer Class method that starts sending packages:

public void executa(String host, int porta, String arquivo) throws ClassNotFoundException {
    try {
        InetAddress addr = InetAddress.getByName(host);
        this.porta = porta;
        this.caminho = arquivo;
        this.host=host;           
        //Fazendo HandShake
        Pacote pct = new Pacote(nSeq,ack,(short)2);
        DatagramPacket envio = new DatagramPacket(Manipulador.objectToByte(pct), 12, addr, porta);
        client = new DatagramSocket();
        //primeira msg
        client.send(envio);

The first package is sent and then the error happens when it arrives at the server, in the thread that receives the packages:

public void run() {
    for (DatagramPacket pkg : servidor.getPacotes()) {
        try {

            Pacote pct = (Pacote) Manipulador.converterParaObject(pkg.getData());
            int flag = pct.getFlag();

When converting the received bytes to the Package object. I had put a println after receiving the server response that never runs, so I realized that the error happens in the first upload.

  • By doing a little research, this seems to be a problem with serialization and not necessarily the way you’re doing the conversion. Some class of your project implements the interface Serializable?

  • Yes, the package class, which is the object I send via udp connection.

  • It only implements Serializable and nothing else? If yes, nor need post. Also, post the class that sends via udp.

  • Only implements serializable.

1 answer

0

I had this same problem and solved it as follows

   Object ObjetoExemplo = new object(); *// este objeto é só um exemplo*
   byte[] EXAMPLE_DATA = gson.toJson(ObjetoExemplo).getBytes(StandardCharsets.UTF_8);

remember to use the google library Gson

Browser other questions tagged

You are not signed in. Login or sign up in order to post.