Serializing an object that contain an array of Strings
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Hassan_Ismaiel
Posted On:   Wednesday, July 24, 2002 07:31 AM

Hi,

I have an object that implements the 'Serializable' interface. I succeeded in serializing this object when it contained primitive types and arrays of 'int'. When I use an array of "String"s, serialization fails and I get the exception "InvalidClassException".


As far as I know, an array is serializable if its items are serializable, and Strings are so.


I would be grateful if you could tell what I have done wrong.

Thanks

Re: Serializing an object that contain an array of Strings

Posted By:   Hassan_Ismaiel  
Posted On:   Wednesday, July 24, 2002 09:22 AM

Sorry my mistake, Its ok now..
I was trying to serialize an object to a String. This String can then be used anywhere (e.g. in a cookie).


Here is what I did:


First, Use "ByteArrayOutputStream" with "ObjectOutputStream" to get a ByteArray representing the object to be serialized -or a String using "ByteArrayOutputStream.toString()" function. The resultant String can be used to de-serialize the object by converting the String to a byte array -using String.toBytes()- and then using "ByteArrayInputStream" with "ObjectOutputStream" to retrieve the object.


This would only work if the object does not contain arrays of non-primitive types. The solution was to specify the character encoding of "ISO8859_1" when converting between ByteArrays and Strings.


i.e. ByteArrayOutputStream.toString("ISO8859_1") and
String.toBytes("ISO8859_1").


I don't know why "ISO8859_1" though, maybe because I'm using Windows.


Hope this is useful to someone.
About | Sitemap | Contact