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
its nice..
ReplyDeleteThanQ dude... ;)
Deletegood explanation dude...
ReplyDeleteThankQ prasad... :)
DeletePlease help me I have 9 errors...
ReplyDeleteXMLtoJsonConverter2.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
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.
DeleteAfter downloading, add it in your classpath.
Underscore-java has static method U.xmlToJson(xml);
Deleteimport java.io.IOException;
ReplyDeleteimport 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();
}
}
thanks buddy
DeleteWhere to place the .XML file..?
ReplyDeleteError:(22, 47) java: cannot find symbol
symbol: method read(java.lang.String)
location: class net.sf.json.xml.XMLSerializer
i have same error. please help.
DeleteThis comment has been removed by the author.
DeleteThis comment has been removed by the author.
Deleteput under /src folder in your eclipse project
ReplyDeleteHi, the output is not formatted. Is there anyway we get formatted output without extra characters like @id
ReplyDeletePlease review this, it indicates there is some bug in this lib ??
ReplyDeletehttp://stackoverflow.com/questions/5113711/convert-xml-to-json-format
DeleteHow 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.
ReplyDeletePut the file in the /src folder in your Eclipse project.
DeleteIt's giving null point error because it can't locate the file.
This comment has been removed by the author.
ReplyDeleteIf 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
ReplyDeleteI got this error please help
ReplyDeleteException 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
getting null pointer exception
ReplyDeletegetting null pointer exception
ReplyDeletejava.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)
I am also getting the null pointer exception:
Deletejava.lang.NullPointerException
at JSONtoXML.getJsonfromXml(JSONtoXML.java:18)
at JSONtoXML.main(JSONtoXML.java:36)
Hello Naveen,
ReplyDeleteI 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.
This comment has been removed by the author.
ReplyDeleteif any body need Local file Try this..its working
ReplyDeleteFileInputStream 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);
book node is not there
ReplyDeleteVery useful information that you have shared and it is very useful to me. Thanks for sharing the information with us.
ReplyDeletekindle mobi formatting services