There maybe an instance where you are already working with xml within an existing webservice and a client is demanding a lighter weight format JSON to be consumed by a REST client. JSON is an easy to read, write and parse format by humans and machines. This example will show how convert xml to from json using Xstream. XStream is a java library with a primary purpose to convert Java Objects into XML and back but was designed with a plugable architecture to provide alternative formats. XStream currently is shipped with JsonHierarchicalStreamDriver which will require a new maven dependency in your project.
<dependency>
<groupId>org.codehaus.jettison</groupId>
<artifactId>jettison</artifactId>
<version>1.3.6</version>
</dependency>
Setup
Defining a java object and displaying a pretty print json and xml used in the snippets below.
POJO
class Status {
String status_code;
String sub_code;
String message;
public Status(String status_code, String sub_code, String message) {
super();
this.status_code = status_code;
this.sub_code = sub_code;
this.message = message;
}
}
XML
String XML ="<com.levelup.java.json.XMLToFromJSONXStream_-Status>\n"+
" <status__code>400</status__code>\n"+
" <sub__code>120</sub__code>\n"+
" <message>Query param start_index out of bounds.</message>\n"+
" <outer-class/>\n"+
"</com.levelup.java.json.XMLToFromJSONXStream_-Status>";
JSON
String JSON = "{\"com.levelup.java.json.XMLToFromJSONXStream$Status\":"
+ "{\"status_code\":400,\"sub_code\":120,\"message\":"
+ "\"Query param start_index out of bounds.\",\"outer-class\":\"\"}}";
Covert xml to JSON
@Test
public void convert_xml_to_json() {
// create xstream object for reading xml
XStream xstream = new XStream();
xstream.setMode(XStream.NO_REFERENCES);
Status status = (Status) xstream.fromXML(XML);
// create a new xstream object w/json provider
XStream xstreamForJson = new XStream(new JettisonMappedXmlDriver());
xstreamForJson.setMode(XStream.NO_REFERENCES);
xstream.alias("status", Status.class);
assertEquals(JSON, xstreamForJson.toXML(status));
}
Covert json to xml
@Test
public void convert_json_to_xml() {
// create a new xstream object w/json provider
XStream xstreamForJson = new XStream(new JettisonMappedXmlDriver());
xstreamForJson.setMode(XStream.NO_REFERENCES);
xstreamForJson.alias("status", Status.class);
Status status = (Status) xstreamForJson.fromXML(JSON);
// create xstream object for reading xml
XStream xstream = new XStream();
xstream.setMode(XStream.NO_REFERENCES);
assertEquals(XML, xstream.toXML(status));
}