Sunday, August 7, 2016

Learn XML and JSON basics with examples

JSON Basics:-

JSON is javascript Object Notation. JSON is the independent format for exchanging data JSON is a simple format which contains key-pair values. JSON and XML are data formats used to transfer data between different systems of enterprise applications. JSON is lightweight and simple to read

JSON Sample data file

{
        "id" : 1.0,
        "name" : "Kiran",
        "sal" : 5000,
    }

XML Basic meaning:-

XML is extensive markeuplanguage which start and end tag and follows certain data validations. XML file can be validates with XML Schema. XML files has data attributes. Reading xml is very easy as most of browsers and editors support simple clicable readable format.

xml sample data file:

<main>
<subtag>Sub tag<subtag>
</subtag></subtag>
</main>

Most of the companies which offer REST APIS expose the data in either XML or JSON. Facebook and Twitter expose their REST API using JSON only.
Clients consume those REST API's and use programming technique to process.

Difference between JSON and XML, pros and cons 


JSON XML
Abbreviated as Javascript Simple notation language Abbreviated as Extensible Markup Language
Markup language Meta Language
Easy to understand and lightweight Complex to read and understand
Easy to parse JSON formats Difficult to parse XML
End tags are available Each tag has an end tag
Human readable /td>Less human readable
XML and JSON common capabilities

  1. Both describe hierarchical data.
  2. Both are easy to learn and understand Language independent.
  3. Both are used to share data between different systems
  4. Both have support in all languages 


In below, We are going to discuss about how to convert XML to JSON to/from in Java. We have many ways to convert to do it in java

How to convert JSON to XML in java

com.gson.gson library provides for reading JSON object and XML class will convert into XML object
import org.json.JSONObject;
import org.json.XML;

public class JsonToXmlConvert {
 public static void main(String[] args) throws Exception {
  String jsonObject = "{'json key':'json value'}";  
  JSONObject json = new JSONObject(jsonObject);
  String xml = XML.toString(json);

 }
}

How to Convert XML to JSON in java? 

It is very simple to convert from XML and JSON in java.org.json.json library provides API to do this. First get dependency org.json.json library if it maven project else, You need this jar file in your classpath.
String xmlInString = ");";
JSONObject jsonObject = XML.toJSONObject(xmlInString);
System.out.println(jsonObject
{"emp": {
    "name": "kiran",
}}
Please share this post if you liked it.