-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.

2
  • I tried that. It only works for a single object or objects, but not foe nested objects like List<Animal> Commented Apr 8, 2015 at 3:03
  • Again I tried the code you suggested. It throws java.lang.ClassCastException: [B cannot be cast to java.util.List Commented Apr 8, 2015 at 3:11

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

You have to explain about your code for better understanding.
baos.close() is redundant here.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.