I suggest you to use some standard format, such as YAML or aforementioned JSON or XML. If your objects form a hierarchical structure without circular dependencies, I'd choose JSON and use Jackson JSON processor - is actively developed and easy to use.
If your objects have circular dependencies, I'd choose YAML, because it can handle then using references, so it'll work even if you have complex object structures. SnakeYAML seems to be a good choice.
I was keen to test another library yamlbeans to see how it handles circular dependencies, so I made a small example for myself. Here it is:
// YamlEx.java
import java.io.*;
import java.util.*;
import com.esotericsoftware.yamlbeans.*;
public class YamlEx {
public static void main(String argv[])
throws Exception
{
Person p1 = new Person("John");
Person p2 = new Person("Paul");
Person p3 = new Person("Bob");
// create a circular dependencies, even to self (p1-p1)
p1.setFriends2(p2, p1, p3);
p2.setFriends2(p1);
p3.setFriends2(p1, p2);
// serialize
CharArrayWriter w = new CharArrayWriter();
YamlWriter writer = new YamlWriter(w);
writer.write(p1);
writer.close();
// print it to the console
System.out.println(w.toString());
// read it again
Reader r = new CharArrayReader(w.toCharArray());
YamlReader reader = new YamlReader(r);
p1 = reader.read(Person.class);
reader.close();
System.out.println(String.format("%s's friends: %s",
p1.name, p1.getFriends() ));
}
}
// Person.java
import java.util.*;
public class Person {
// A public field as a test.
public String name;
public Person() {
}
public Person(String name) {
this.name = name;
}
public String toString() {
return name;
}
// A set/get pair as a test.
private List<Person> friends0;
public List<Person> getFriends() {
return friends0;
}
public void setFriends(List<Person> p) {
this.friends0 = p;
}
public void setFriends2(Person... p) {
setFriends(Arrays.asList(p));
}
}
Works as expected:
&1 !Person
name: John
friends: !java.util.Arrays$ArrayList
- &2 !Person
name: Paul
friends: !java.util.Arrays$ArrayList
- *1
- *1
- !Person
name: Bob
friends: !java.util.Arrays$ArrayList
- *1
- *2
John's friends: [Paul, John, Bob]