How to deserialize from a String
1 posts in topic
Flat View  Flat View

Posted By:   cedric_dumetz
Posted On:   Tuesday, October 16, 2001 06:21 AM

I serialized an Object with ObjectOutputStream

After, I converted this stream to a String and I put it on an URL.

Now I would like take this String from the URL.

I saw that I can use a Reader to convert my String into Reader but how convert this Reader into InputStream and thereby use ObjectInputStream.

Maybe I use a wrong way because I don't really understand serialisation and stream ??

thanks a lot


Re: How to deserialize from a String

Posted By:   Randy_McLaughlin  
Posted On:   Monday, October 22, 2001 08:29 AM

To create a byte array containing the serialized representation of an object graph, create a ByteArrayOutputStream object and then pass it as an argument to the ObjectOutputStream constructor. Once you've serialized the object, flush the ObjectOutputStream. You can then obtain a byte array containing the serialized representation using the the ByteArrayOutputStream's toByteArray method. You can also obtain a String from the ByteArrayOutputStream by using its toString method.

You could later deserialize the byte array using the ByteArrayInputStream and ObjectInputStream classes. Pass the byte array as an argument to the ByteArrayInputStream constructor. Pass the newly created ByteArrayInputStream object as an argument to the ObjectInputStream constructor. You can then deserialize the object graph using the readObject method.

Here's some code:

// write the 'yourObject' object to a byte array called 'byteArray'.
ByteArrayOutputStream ostream = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(ostream);
byte[] byteArray= ostream.toByteArray();

// store, copy or transfer byteArray as needed without changing its content

// deserialize the byte array
ObjectInputStream istream = new ObjectInputStream(byteArray);
ObjectInputStream in = new ObjectInputStream(istream);
Object deserializedObject= in.readObject();

The byte array contains binary data. You must assure that the byte array passed to the ObjectInputStream constructor is an exact bit-by-bit copy of the array obtained from the ByteArrayOutputStream. It may be converted to a string, but you must assure that the same encoding is used when converting to a string and when converting back to a byte array. In addition, to use the resulting string in a URL, the java.net.URLEncoder class should be used to encode characters that would otherwise be illegal in a URL.

About | Sitemap | Contact