Thursday, January 30, 2014

Java library to convert XML to JSON

Recently I wanted to convert some XMLs to JSON messages. I came across this library called JSON-Java and found it very useful.
import org.json.JSONException;
import org.json.JSONObject;
import org.json.XML;

public class Main {

    public static int PRETTY_PRINT_INDENT_FACTOR = 4;
    public static String TEST_XML_STRING =
            "\n" +
                    "\n" +
                    "Belgian Waffles\n" +
                    "$5.95\n" +
                    "\n" +
                    "Two of our famous Belgian Waffles with plenty of real maple syrup\n" +
                    "\n" +
                    "650\n" +
                    "\n" +
                    "\n" +
                    "Strawberry Belgian Waffles\n" +
                    "$7.95\n" +
                    "\n" +
                    "Light Belgian waffles covered with strawberries and whipped cream\n" +
                    "\n" +
                    "900\n" +
                    "\n" +
                    "";

    public static void main(String[] args) {
        try {
            JSONObject xmlJSONObj = XML.toJSONObject(TEST_XML_STRING);
            String jsonPrettyPrintString = xmlJSONObj.toString(PRETTY_PRINT_INDENT_FACTOR);
            System.out.println(jsonPrettyPrintString);
        } catch (JSONException je) {
            System.out.println(je.toString());
        }
    }
}
The XML:
<breakfast_menu>
<food>
<name>Belgian Waffles</name>
<price>$5.95</price>
<description>
Two of our famous Belgian Waffles with plenty of real maple syrup
</description>
<calories>650</calories>
</food>
<food>
<name>Strawberry Belgian Waffles</name>
<price>$7.95</price>
<description>
Light Belgian waffles covered with strawberries and whipped cream
</description>
<calories>900</calories>
</food>
</breakfast_menu>
JSON:
{"breakfast_menu": {"food": [
    {
        "price": "$5.95",
        "description": "Two of our famous Belgian Waffles with plenty of real maple syrup",
        "name": "Belgian Waffles",
        "calories": 650
    },
    {
        "price": "$7.95",
        "description": "Light Belgian waffles covered with strawberries and whipped cream",
        "name": "Strawberry Belgian Waffles",
        "calories": 900
    }
]}}

3 comments:

Softwares said...

I added the required jar files. But i am getting this exception

Exception in thread "main" java.lang.UnsatisfiedLinkError: org.json.JSONTokener.more()Z
at org.json.JSONTokener.more(Native Method)
at org.json.XML.toJSONObject(XML.java:368)
at com.gm.tmt.test.ConvertXMLtoJSON.main(ConvertXMLtoJSON.java:24)
.
Please help

Lawrence Thanakumar said...

No, It is working perfectly

Unknown said...

Used this (slightly edited because I just needed the raw JSON-string) in a project. Works like a charm. Great, thanks!!!