Serializable java object to a string

B

bob smith

What's the easiest way to convert a Serializable java object to a string?

Maybe a hex string or base64?

Thanks.
 
M

markspace

What's the easiest way to convert a Serializable java object to a string?

Maybe a hex string or base64?

Thanks.


javax.xml.bind.DatatypeConverter contains both hex and base 64
conversion methods to help you out.
 
A

Arne Vajhøj

What's the easiest way to convert a Serializable java object to a string?

Maybe a hex string or base64?

Write the object to an ObjectOutputStream wrapped around
a ByteArrayOutputStream, retrieve the byte array and
convert it to hex or base64.

Arne
 
A

Arne Vajhøj

Write the object to an ObjectOutputStream wrapped around
a ByteArrayOutputStream, retrieve the byte array and
convert it to hex or base64.

Example:

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io_ObjectInputStream;
import java.io_ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.DatatypeConverter;

public class SerFun {
public static String anySerialize(Object o) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(o);
oos.close();
return DatatypeConverter.printBase64Binary(baos.toByteArray());
}
public static Object anyDeserialize(String s) throws IOException,
ClassNotFoundException {
ByteArrayInputStream bais = new
ByteArrayInputStream(DatatypeConverter.parseBase64Binary(s));
ObjectInputStream ois = new ObjectInputStream(bais);
Object o = ois.readObject();
ois.close();
return o;
}
public static void main(String[] args) throws Exception {
List<Data> lst = new ArrayList<Data>();
lst.add(new Data(1, "A"));
lst.add(new Data(2, "BB"));
lst.add(new Data(3, "CCC"));
System.out.println(lst);
String s = anySerialize(lst);
@SuppressWarnings("unchecked")
List<Data> lst2 = (List<Data>)anyDeserialize(s);
System.out.println(lst2);
}
}

Arne
 
A

Arne Vajhøj

Write the object to an ObjectOutputStream wrapped around
a ByteArrayOutputStream, retrieve the byte array and
convert it to hex or base64.

I will recommend XML serialization over binary serialization if
the serialized version wil be persisted!

Arne
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top