Deserialization of a String
Hello,
What I want to do sounds quite easy, but im just getting errors
I have an API which stores and reads Strings in a property file. I use the API to store an object as a String by serializing it. This seems to be working.
I have problems to deserialze this String an obtain the object.
I wrote this code:
byte[] buff = objectString.getBytes();//1.
ByteArrayInputStream bis =new ByteArrayInputStream(buff);//2.
ObjectInputStream in =new ObjectInputStream(bis);//3.
MyObject ob = (MyObject)in.readObject();//4.
In 2. i get an Exception
java.io.StreamCorruptedException: invalid stream header: 5B424031
It cannot be hard to deserialize a String, but in the net I just found examples how read from a file or from a server.
This should be much eayser. I磎 lacking of ideas what to try else.
[1098 byte] By [
Witroba] at [2007-11-27 5:48:34]

# 1
What is the type of objectString? It looks like it might be a string already, in which case you're wasting your time.
If not, how do you get your serialised object into "objectString".
In short, we need to see a bit more code (i.e. the stuff before this) and perhaps the serialisation code too to see if you've made any gross errors.
# 2
thePropManager is a property manager - part of the API that i am using
public DashboardConfig restoreConfig(){
String objectString = thePropManager.getString("config") ;
DashboardConfig conf;
try {
byte[] buff = objectString.getBytes();
ByteArrayInputStream bis = new ByteArrayInputStream(buff);
ObjectInputStream in = new ObjectInputStream(bis);
conf = (DashboardConfig)in.readObject();
in.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
conf = new DashboardConfig();
} catch (IOException e) {
e.printStackTrace();
conf = new DashboardConfig();
}
return conf;
}
serialization:
public void saveConfig() {
DashboardConfig conf = this.getTheConfig();
String key = "config";
ByteArrayOutputStream bos = new ByteArrayOutputStream() ;
try {
ObjectOutput out = new ObjectOutputStream(bos) ;
out.writeObject(conf);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
byte[] buf = bos.toByteArray();
String value = buf.toString();
thePropManager.putString(key, value);
}
# 5
> You can't do that. java.lang.String is not a
> container for binary data. The round-trip to and from
> binary data is not lossless. If you must do this
> you'll have to base64-encode the binary data.
That might be the problem. How u mean that i have to encode the binary data in this case?
encode the String before saving it via thePropManager?
Thanks