Saving/Retrieving the java object as/from xml string

Apparently this is extremely easy :). I wanted to save an object in xml format in order to later recover the object. The coading involves only a couple of lines of code. Following is an example class I wrote on how to do that. As you can see I’ve included the xml encoding & decoding methods (toString() and the getMyObject()) inside the same class which of course can be done outside the class also.

package a.b.c;

import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.util.HashMap;
import java.util.Map;

public class MyClass {
	private String name;
	private int age;
	private Map friends=new HashMap();

	public void setAge(int age) {this.age = age;}
	public int getAge() {return age;}
	public void setName(String name) { = name;}
	public String getName() {return name;}
	public void setFriends(Map friends) {this.friends = friends;}
	public Map getFriends() {return friends;}

        // from here starts the xml encoding/decoding
	public String toString(){
	   StringOutputStream fos = new StringOutputStream();
           XMLEncoder xenc = new XMLEncoder(fos);
           return fos.getString();
	public static MyClass getMyClass(String xmlObjStr){
	   XMLDecoder decoder = new XMLDecoder(new ByteArrayInputStream(xmlObjStr.getBytes()));
	   MyClass p = (MyClass)decoder.readObject();
	   return p;
	private class StringOutputStream extends OutputStream {
	  StringBuilder mBuf = new StringBuilder();
	  public void write(int bytes) throws IOException {mBuf.append((char) bytes);}
	  public String getString() {return mBuf.toString();}
        // xml encoding/decoding ends

then by simply just calling toString() method of an object of above class you can get the xml representation of the object (save it to a file/database if u want) and recreate an object of the type by passing this xml to getMyClass() method.


Tags: , , ,

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: