Learn XML and JSON basics with examples

In this blog post, We will discuss XML and JSON basics, pros/cons and also convert JSON to XML or XML to JSON in java.

JSON Basics

JSON is abbreviated as 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

Following is sample JSON file which contains simple key and value pairs

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

XML Basics 

XML is extensive markup language which starts and end tag and follows certain data validations. XML file can be validates with XML Schema. XML files have data attributes. Reading XML is very easy as most of browsers and editors support the simple clickable readable format.

XML sample data file:

<subtag>Sub tag<subtag>  

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 

Each one has advantages and disadvantages and listed below.



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 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 API for reading JSON object and to 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);  

{"emp": {  
    "name": "kiran",  

Please share this post if you liked it.

Similar Posts