This can be demonstrated by using a JSON Org class simply called XML. This class, so the manual says, provides a bunch of static methods that convert XML to JSON and JSON to XML.
Below is a contrived WineSeach XML document that I’ve used in a previous blog - and you can assume that it’s defined by the appropriate XML schema:
<?xml version="1.0" encoding="UTF-8"?> <WineSearch xmlns="http://marin.tips.spring.webservice/schemas"> <Request> <Country>France</Country> </Request> <Response country="France"> <Wine> <Name>Chateau Roger</Name> <Origin>Bordeaux</Origin> <Strength>11.3</Strength> <Colour>Red</Colour> </Wine> <Wine> <Name>Gewurztraminer</Name> <Origin>Alsace</Origin> <Strength>12.4</Strength> <Colour>White</Colour> </Wine> </Response> </WineSearch>
The Java code below takes the XML above, converts it to JSON and back to XML.
public static void main(String[] args) throws JSONException {
System.out.println("This is the input: " + XML_INPUT);
String json = xml2json(XML_INPUT);
json2xml(json);
}
private static String xml2json(String xmlIn) throws JSONException {
JSONObject obj = XML.toJSONObject(xmlIn);
System.out.println("JSON is: " + obj);
return obj.toString();
}
private static void json2xml(String jsonIn) throws JSONException {
JSONObject obj = new JSONObject(new JSONTokener(jsonIn));
String xml = XML.toString(obj);
System.out.println("XML is: " + xml);
}
The JSON that this code will produce with the WineSearch input is:
{"WineSearch":{"Response":{"Wine":[{"Name":"Chateau Roger","Colour":"Red","Strength":11.3,"Origin":"Bordeaux"},{"Name":"Gewurztraminer","Colour":"White","Strength":12.4,"Origin":"Alsace"}],"country":"France"},"Request":{"Country":"France"},"xmlns":"http://marin.tips.spring.webservice/schemas"}}
and using this to produce XML, we get the following:
<WineSearch> <Response> <country>France</country> <Wine> <Name>Chateau Roger</Name> <Colour>Red</Colour> <Strength>11.3</Strength> <Origin>Bordeaux</Origin> </Wine> <Wine> <Name>Gewurztraminer</Name> <Colour>White</Colour> <Strength>12.4</Strength> <Origin>Alsace</Origin> </Wine> </Response> <Request> <Country>France</Country> </Request> <xmlns>http://marin.tips.spring.webservice/schemas</xmlns> </WineSearch>
…which doesn’t really bare that much resemblance to the original and wouldn’t pass our imaginary schema.
This doesn’t mean that the JSON Org XML class is bad, it’s just that being a JSON class it doesn’t know about XML schemata, and neither should it.
2 comments:
Great Blog with very good posts .Can you please tell me that how much time you take to create this wonderful blog,although i am new on internet but your work is very good and i appreciate your work.
EDI
Lachlan,
Glad you like the blog. It takes me several man hours to write a blog depending upon it's complexity and the amount of code that's needed. I usually do them in my spare time over a period of about two weeks.
Post a comment