Serialize to json with XstreamFrom WikiJavabuy this book In this example I'll show you how to serialize and de-serialize any object using the Xstream Library.
The Article
Xstream is a very powerful library and it makes it very easy to serialize and de-serialize any object you want. In this example I create a Person object and show you what to do with it. Serializing an object to a Json StringThe interface of Xstream is very simple, it's all done using the You just need to initialize it with the proper driver. Luckily Xstream comes bundled with the drivers of all the most used XML APIs. You can also XStream xstream = new XStream(new JettisonMappedXmlDriver()); The following line is optional. xstream.setMode(XStream.NO_REFERENCES); It tells Xstream not to generate references in the resulting Json String, this means that if the object structure contains twice the same object the whole object is written twice in the string. If you remove this setting you'll probably get in the resulting JSon something like:
For example the following two commands are used to specify an alias for the classes (this alias has to be specified also in the de-serializer). If you don't include these alias definitions then the resulting Json will contain the fully qualified names for the classes. xstream.alias("person", Person.class); xstream.alias("address", Address.class); The real magic is done with the following command. Which is pretty simple to understand, regardless the complexity it hides. String json = xstream.toXML(person); extracting the Json to an objectThe deserializer method is pretty straightforward, especially after seeing the serializing one. All you have to do is to initialize the XStream xstream = new XStream(new JettisonMappedXmlDriver()); xstream.setMode(XStream.NO_REFERENCES); // optional to make the output more concise xstream.alias("person", Person.class); xstream.alias("address", Address.class); and then call the method: Object com.thoughtworks.xstream.XStream.fromXML(String xml) And cast the resulting Object to the Person class. As follows: Person newPerson = (Person) xstream.fromXML(json); ConclusionsTo see the complete code for this example download it from the Subversion repository as mentioned above. |
