Press enter to see results or esc to cancel.


Java program to Convert JSON to XML


In the video I have shown you step by step, How you can code a simple java program that can convert JSON to XML.
You need to import jar file to classpath in eclipse. You can download the jar file here java-json.jar
Source JSON example.

 
{
    "glossary": {
        "title": "example glossary",
		"GlossDiv": {
            "title": "S",
			"GlossList": {
                "GlossEntry": {
                    "ID": "SGML",
				"SortAs": "SGML",
				"GlossTerm": "Standard Generalized Markup Language",
				"Acronym": "SGML",
				"Abbrev": "ISO 8879:1986",
				"GlossDef": {
                        "para": "A meta-markup language, used to create markup languages such as DocBook.",
				"GlossSeeAlso": ["GML", "XML"]
                    },
				"GlossSee": "markup"
                }
            }
        }
    }
}
 

The below program can convert JSON to XML.

package com.chillyfacts.com;
import org.json.JSONObject;
import org.json.XML;
public class Convert_JSON_TO_XML {
    public static void main(String[] args) {

        String json_value = "{ \"glossary\": { \"title\": \"example glossary\", \"GlossDiv\": { \"title\": \"S\", \"GlossList\": { \"GlossEntry\": { \"ID\": \"SGML\", \"SortAs\": \"SGML\", \"GlossTerm\": \"Standard Generalized Markup Language\", \"Acronym\": \"SGML\", \"Abbrev\": \"ISO 8879:1986\", \"GlossDef\": { \"para\": \"A meta-markup language, used to create markup languages such as DocBook.\", \"GlossSeeAlso\": [\"GML\", \"XML\"] }, \"GlossSee\": \"markup\" } } } } }";

        System.out.println(Convert_JSON_TO_XML.convert_json(json_value));

    }
    public static String convert_json(String json_value) {
        String xml = "";
        try {
            JSONObject jsoObject = new JSONObject(json_value);
            xml = xml + XML.toString(jsoObject);
        } catch (Exception e) {
            System.out.println(e);
        }
        xml = xml + "";
        return xml;
    }
}

XML format of the JSON after conversion is ,

 
<Response> <glossary> <title>example glossary</title> <GlossDiv> <GlossList> <GlossEntry> <SortAs>SGML</SortAs> <GlossDef> <GlossSeeAlso>GML</GlossSeeAlso> <GlossSeeAlso>XML</GlossSeeAlso> <para>A meta-markup language, used to create markup languages such as DocBook.</para> </GlossDef> <GlossSee>markup</GlossSee> <GlossTerm>Standard Generalized Markup Language</GlossTerm> <ID>SGML</ID> <Acronym>SGML</Acronym> <Abbrev>ISO 8879:1986</Abbrev> </GlossEntry> </GlossList> <title>S</title> </GlossDiv> </glossary> </Response>

Comments

Comments are disabled for this post