Reputation: 229
I have an Object array of Object array. I want to convert it into a byte array and then receive it back as array of Object array. I have used theObjectOutputStream
in conjunction with the ByteArrayOutputStream
to convert it into a byte array:
ByteArrayOutputStream b = new BAOS();
ObjectOutputStream o = new OOS();
o.writeObject(obj) // obj being the array
Then when I try to read it, all that I get is the content of the first array only. Also the size of the object array received is equal to the size of the individual arrays.
I have tried using iteration for writeObject()
but to no avail.
Ok, so further I have tried the multi dimensional array approach as well:
byte[] firstArr = new byte[1];
oos.writeObject(orgArr[0]);
firstArr = baos.toByteArray();
byte[] secondArr = new byte[1];
oos.writeObject(orgArr[1]);
secondArr = baos.toByteArray();
byte[] combined = new byte[2];
combined[0] = firstArr[0];
combined[1] = secondArr[1];
Both arrays are the same, of same length and both the firstArr
and secondArr
are Object arrays. So, the problem that I have is that when I deserialize it using:
ObjectInputStream ois = new ObjectInputStream(
new ByteArrayInputStream(om.nakedPayload));
Object[] list = (Object[]) ois.readObject();
The length of the array list returned is 38. Which is the length of either of the 2 arrays (firstArr
/secondArr
). Also, the data that it contains is just of the firstArr
. The om.nakedPayload
is the data which I read from a Kafka topic. We have a wrapper written here so essentially, it expects a byte[]
for read/write purposes.
Upvotes: 0
Views: 97
Reputation: 2961
Let's simplify the task and assume your object is Integer, then the code for serializing/deserializing will look like following:
import java.io.*;
public class ArrayOfArrays {
public static void main(String[] args) throws Exception{
String fileName = "myobject.data";
FileOutputStream fileOut = new FileOutputStream(fileName);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
Integer[][] intArray = new Integer[3][3];
intArray[0] = new Integer[] {11, 12, 13};
intArray[1] = new Integer[] {21, 22, 23};
intArray[2] = new Integer[] {31, 32, 33};
out.writeObject(intArray);
FileInputStream fileIn = new FileInputStream(fileName);
ObjectInputStream in = new ObjectInputStream(fileIn);
Integer[][] intArrayIn = (Integer[][]) in.readObject();
}
}
This will give same "array of arrays" object back. Next step we can replace Integer with any class which implements marker interface java.io.Serializable.
All non-transient fields will be involved in serialization/deserialization and restored along with root "array of arrays" object.
Upvotes: 1