-2

I have a List<Animal> that i want to send as a SOAP response to the client but the send method requires byte[] and deserialize in the client.

Can anyone tell me how to convert my List<Animal> to byte[] and convert the byte[] back to the List<Animal>.

I know there is lots of questions like this in this site, but I am confuse with the answers. I tried a lot of them but none of the worked for me.

user1036645
  • 63
  • 2
  • 8

2 Answers2

2

It depends on Animal. If it is Serializable you can use Java Serialization mechanizm https://docs.oracle.com/javase/tutorial/jndi/objects/serial.html.

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
0
public static byte[] objectToByteArray(Object obj) throws Exception {
    byte[] bytes = null;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(obj);
    bytes = baos.toByteArray();
    oos.close();
    return bytes;
}

public static Object byteArrayToObject(byte[] buffer) throws Exception {
    Object ob = null;
    ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(
            buffer));
    ob = ois.readObject();
    ois.close();
    return ob;
}
Thomas Zhang
  • 200
  • 2
  • 8