Saturday 27 April 2013

XML To JSON Conversion



Hi friends,

I would like to share converting XML into JSON format.

XML: 

  • XML (Extensible Markup Language) is a mark-up language that defines the set of rules for encoding document in Human &Machine readable format.
  • XML mainly emphasizes on Simplicity, Generality and Usability over the Internet. 
  • XML is a textual data format with strong support for all the languages of the World.
JSON:
  • JSON (JavaScript Object Notation) is a text-based open standard designed for Human-Readable data interchange.
  • Even JSON is javaScript specific, it is language-independent with parsers available for many languages.
  • JSON format is often used over network connection for serializing and transmitting structured data .

On keeping Pros and Cons of them a-part, this is the scenario which is very often needed for developing Applications (Mainly in Web environment).


Pre-Requisites:
I used net.sf.json-lib for JSON support. You can download from here.
Json-lib should contain the below dependencies in classpath:
  • commons-lang
  • commons-beanutils
  • commons-collections
  • commons-logging
  • ezmorph

Below is code for Converting XML to JSON format:


package testapp;
import java.io.InputStream;
import java.net.URL;
import net.sf.json.JSON;
import net.sf.json.xml.XMLSerializer;
import org.apache.commons.io.IOUtils;
/**
 * @author naveen.k
 */
public class XMLtoJsonConverter {
    private URL url = null;
    private InputStream inputStream = null;    
    public void getXMLfromJson() {
        try{
            url = XMLtoJsonConverter.class.getClassLoader().getResource("sample.xml");
            inputStream = url.openStream();
            String xml = IOUtils.toString(inputStream);
            JSON objJson = new XMLSerializer().read(xml);
            System.out.println("JSON data : " + objJson);
        }catch(Exception e){
            e.printStackTrace();
        }finally{
     try {
                if (inputStream != null) {
                    inputStream.close();
                }
                url = null;
            } catch (IOException ex) {}
        }
    }
    public static void main(String[] args) {
        new XMLtoJsonConverter().getXMLfromJson();
    }
}


Place the sample xml in the specified path

sample.xml
==========



   
      Gambardella, Matthew
      XML Developer's Guide
      Computer
      44.95
      2000-10-01
      An in-depth look at creating applications 
      with XML.
   
   
      Ralls, Kim
      Midnight Rain
      Fantasy
      5.95
      2000-12-16
      A former architect battles corporate zombies, 
      an evil sorceress, and her own childhood to become queen 
      of the world.
   

 


Output for the above specified xml is given below

OUTPUT:
=========

xml to json: [{"@id":"bk01","author":"Gambardella, Matthew","title":"XML Developer's Guide","genre":"Computer","price":"44.95","publish_date":"2000-10-01","description":"An in-depth look at creating applications \n      with XML."},{"@id":"bk02","author":"Ralls, Kim","title":"Midnight Rain","genre":"Fantasy","price":"5.95","publish_date":"2000-12-16","description":"A former architect battles corporate zombies, \n      an evil sorceress, and her own childhood to become queen \n      of the world."}]
 


Formated JSON data as  per the Output is given below

JSON DATA:
===========
[
{
"@id":"bk01",
"author":"Gambardella, Matthew",
"title":"XML Developer's Guide",
"genre":"Computer",
"price":"44.95",
"publish_date":"2000-10-01",
"description":"An in-depth look at creating applications \n with XML."
},
{
"@id":"bk02",
"author":"Ralls, Kim",
"title":"Midnight Rain",
"genre":"Fantasy",
"price":"5.95",
"publish_date":"2000-12-16",
"description":"A former architect battles corporate zombies, \n an evil sorceress, and her own childhood to become queen \n of the world."
}
]
For JSON To XML Conversion Check here

30 comments:

  1. Please help me I have 9 errors...

    XMLtoJsonConverter2.java:4: error: package net.sf.json does not exist
    import net.sf.json.JSON;
    ^
    XMLtoJsonConverter2.java:5: error: package net.sf.json.xml does not exist
    import net.sf.json.xml.XMLSerializer;
    ^
    XMLtoJsonConverter2.java:6: error: package org.apache.commons.io does not exist
    import org.apache.commons.io.IOUtils;
    ^
    XMLtoJsonConverter2.java:15: error: cannot find symbol
    url = XMLtoJsonConverter.class.getClassLoader().getResource("sample.xml");
    ^
    symbol: class XMLtoJsonConverter
    location: class XMLtoJsonConverter2
    XMLtoJsonConverter2.java:17: error: cannot find symbol
    String xml = IOUtils.toString(inputStream);
    ^
    symbol: variable IOUtils
    location: class XMLtoJsonConverter2
    XMLtoJsonConverter2.java:18: error: cannot find symbol
    JSON objJson = new XMLSerializer().read(xml);
    ^
    symbol: class JSON
    location: class XMLtoJsonConverter2
    XMLtoJsonConverter2.java:18: error: cannot find symbol
    JSON objJson = new XMLSerializer().read(xml);
    ^
    symbol: class XMLSerializer
    location: class XMLtoJsonConverter2
    XMLtoJsonConverter2.java:28: error: cannot find symbol
    } catch (IOException ex) {}
    ^
    symbol: class IOException
    location: class XMLtoJsonConverter2
    XMLtoJsonConverter2.java:32: error: cannot find symbol
    new XMLtoJsonConverter().getXMLfromJson();
    ^
    symbol: class XMLtoJsonConverter
    location: class XMLtoJsonConverter2
    9 errors

    ReplyDelete
    Replies
    1. Add JSON jar in your project. Download it from provided link in the tutorial or you can download from http://mvnrepository.com/artifact/net.sf.json-lib/json-lib.

      After downloading, add it in your classpath.

      Delete
    2. Underscore-java has static method U.xmlToJson(xml);

      Delete
  2. import java.io.IOException;
    import java.io.InputStream;
    import java.net.URL;
    import org.apache.commons.io.IOUtils;
    import org.json.XML;

    public class XMLtoJsonConverter {
    private URL url = null;
    private InputStream inputStream = null;


    public void getXMLfromJson() {
    try{

    url = XMLtoJsonConverter.class.getClassLoader().getResource("article1.xml");
    System.out.println("JSON data : " + url.toString());
    inputStream = url.openStream();
    String xml = IOUtils.toString(inputStream);
    System.out.println("XML data : " + xml);

    // JSON objJson = new XMLSerializer().read(xml);

    org.json.JSONObject objJson = XML.toJSONObject(xml);

    System.out.println("JSON data : " + objJson);

    }catch(Exception e){
    e.printStackTrace();
    }finally{
    try {
    if (inputStream != null) {
    inputStream.close();
    }
    url = null;
    } catch (IOException ex) {}
    }
    }
    public static void main(String[] args) {
    new XMLtoJsonConverter().getXMLfromJson();
    }
    }

    ReplyDelete
  3. Where to place the .XML file..?
    Error:(22, 47) java: cannot find symbol
    symbol: method read(java.lang.String)
    location: class net.sf.json.xml.XMLSerializer

    ReplyDelete
    Replies
    1. i have same error. please help.

      Delete
    2. This comment has been removed by the author.

      Delete
    3. This comment has been removed by the author.

      Delete
  4. put under /src folder in your eclipse project

    ReplyDelete
  5. Hi, the output is not formatted. Is there anyway we get formatted output without extra characters like @id

    ReplyDelete
  6. Please review this, it indicates there is some bug in this lib ??

    ReplyDelete
    Replies
    1. http://stackoverflow.com/questions/5113711/convert-xml-to-json-format

      Delete
  7. How to read the xml file which is in local drive. I gave the path of xml file located in my local drive(D://sample.xml). But im facing NUllPointerException.

    ReplyDelete
    Replies
    1. Put the file in the /src folder in your Eclipse project.
      It's giving null point error because it can't locate the file.

      Delete
  8. This comment has been removed by the author.

    ReplyDelete
  9. If you have a valid dtd file for the xml snippet, then you can easily convert xml to json and json to xml using the open source eclipse link jar. Detailed sample JAVA project can be found here: http://cubicrace.com/2015/06/How-to-convert-XML-to-JSON-format.html

    ReplyDelete
  10. I got this error please help

    Exception in thread "main" java.lang.NoClassDefFoundError: nu/xom/Serializer
    at XMLtoJSONconverter.getXMLfromJson(XMLtoJSONconverter.java:21)
    at XMLtoJSONconverter.main(XMLtoJSONconverter.java:35)
    Caused by: java.lang.ClassNotFoundException: nu.xom.Serializer
    at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
    ... 2 more

    ReplyDelete
  11. getting null pointer exception

    ReplyDelete
  12. getting null pointer exception

    java.lang.NullPointerException
    at utilities.XmlToJson.getXMLfromJson(XmlToJson.java:17)
    at stepDefinitions.PrivacyPolicy.cleanUp(PrivacyPolicy.java:51)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at cucumber.runtime.Utils$1.call(Utils.java:37)
    at cucumber.runtime.Timeout.timeout(Timeout.java:13)
    at cucumber.runtime.Utils.invoke(Utils.java:31)
    at cucumber.runtime.java.JavaHookDefinition.execute(JavaHookDefinition.java:60)
    at cucumber.runtime.Runtime.runHookIfTagsMatch(Runtime.java:223)
    at cucumber.runtime.Runtime.runHooks(Runtime.java:211)
    at cucumber.runtime.Runtime.runAfterHooks(Runtime.java:205)
    at cucumber.runtime.model.CucumberScenario.run(CucumberScenario.java:46)
    at cucumber.runtime.model.CucumberFeature.run(CucumberFeature.java:165)
    at cucumber.runtime.Runtime.run(Runtime.java:121)
    at cucumber.api.cli.Main.run(Main.java:36)
    at cucumber.api.cli.Main.main(Main.java:18)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)

    ReplyDelete
    Replies
    1. I am also getting the null pointer exception:

      java.lang.NullPointerException
      at JSONtoXML.getJsonfromXml(JSONtoXML.java:18)
      at JSONtoXML.main(JSONtoXML.java:36)

      Delete
  13. Hello Naveen,

    I tried to follow along the above the snippet. I was able to get it working. However, i am getting an error "cannot find symbol : method read(String) at line
    JSON objJson = new XMLSerializer().read(xml);
    I have these below imports without any errors.
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.URL;
    import net.sf.json.JSON;
    import net.sf.json.xml.XMLSerializer;
    import org.apache.commons.io.IOUtils;

    Please let me know if you there is something i am missing.

    ReplyDelete
  14. This comment has been removed by the author.

    ReplyDelete
  15. if any body need Local file Try this..its working

    FileInputStream fis = new FileInputStream("D:\\springFiles\\authors.xml");

    String xml = IOUtils.toString(fis, StandardCharsets.UTF_8.name());

    JSON objJson = new XMLSerializer().read(xml);
    System.out.println("JSON data : " + objJson);

    ReplyDelete
  16. Very useful information that you have shared and it is very useful to me. Thanks for sharing the information with us.
    kindle mobi formatting services

    ReplyDelete