Aug 29, 2015

Textual description of firstImageUrl

Data types,Variable and Method declaration in Scala

In previous post we discussed fundamental of Scala and set-up Scala development environment. Here we will walk through various language construct and use REPL(Scala interpreter/interactive shell) to execute the same.

Data types:- 

Scala supports all the basic value types (primitives): Byte, Short, Int, Float, Double, Boolean, and Char.In Scala all the basic types are objects, and they’re defined under the scala package. Byte, Short, Int, Long, and Char are collectively called integral types.
The integer literals(literal is a shorthand way to describe an object) can represent decimal, hexadecimal, and octal numbers.Hexadecimal numbers start with 0x,and Long type add the suffix L or l.
scala> val hexa = 0x25
hexa: Int = 37
scala> val long= 345L
long: Long = 345
Floating-point literals are of type Float when they’re suffixed with F or f and are Double otherwise:
scala> val d = 0.0
d: Double = 0.0
scala> val f = 0.0f
f: Float = 0.0
Create a Double variable with an exponent part. To declare a variable with the value of 1 times 10 to the power of 30 (1 times 10^30), it would look like this:
scala>val exponent = 1e30
exponent: Double = 1.0E30
A character literal is a single character enclosed in quotes.
scala> val capsB = '\102'
capsB: Char = B
Printable Unicode characters can be used as variable and method names. To create a variable name ans with the value 42 using Unicode characters:
scala> val \u0065\u006e\u0079 = 45
eny: Int = 45
String object is created by using the string literal "one" and also using the new keyword, as in new String("one"). A string literal is a sequence of characters in double quotes. The characters are either
printable Unicode characters or escape sequences.
scala> val strMsg = "Hello \"Scala\""
strMsg: String = Hello "Scala"
Scala 2.10 has support for String interpolation,any token prefixed with $ or wrapped with ${...} within the string will be replaced with its corresponding values.
scala> val msgPart = "Nikhil"
msgPart: String = Nikhil
scala> s"Hello, $msgPart"
res0: String = Hello, Nikhil

Variable declaration:- 

Scala gives flexibility to create an immutable(read-only) and mutable(read-write both) variable when you declare it.
1. Using val keyword immutable variable is created(similar to final variables in Java) and var creates mutable variables.The type of variable(or function)is always written after variable and function.
2. No semicolon is required in variable declaration(In Scala, semicolon is not required until multiple statements are written in same line).
3. Scala recommends to use immutable objects whenever possible, Scala as a language doesn’t provide any restrictions.
4.The Scala interpreter infer the type of variable based on the value, but when we would like to, specify the type variable after the variable name, separating it by a colon (:).
Note:- The var and val keywords only specify whether the reference can be changed to refer to a different object (var) or not (val). In following declaration, string array reference cannot be changed but array can be modified. 
scala> val empId = 234;
empId: Int = 234

scala> empId = 234;
<console>:11: error: reassignment to val
       empId = 234;
             ^
Now create an string Array and try to modify variable reference and modify array.
scala> val stringArray:Array[String] = new Array(5);
stringArray: Array[String] = Array(null, null, null, null, null)

scala> stringArray = new Array(3);
<console>:11: error: reassignment to val
       stringArray = new Array(3);

scala> stringArray(0) ="Hello"
scala> stringArray(3) ="Scala"

scala> stringArray
res6: Array[String] = Array(Hello, null, null, Scala, null)
Create mutable object using var, reference variable can be reassigned to some other object of same type(including subclass too.)
scala> var address = "37C, LUY, NYC"
address: String = 37C, LUY, NYC

scala> address = "NYC , 34YU"
address: String = NYC , 34YU

scala> address = 12
<console>:11: error: type mismatch;
 found   : Int(12)
 required: String
       address = 12
                 ^
Declare a variable without assigning a value :- Scala placeholder character (_) to assign a default value.Default value for String is null.
scala> var defaultStr:String = _
defaultStr: String = null
lazily initialize value to a varible:- Using lazy keyword(with val only), we can initialize value of a variable when it is being used.
scala> var one = 1;
one: Int = 1

scala> lazy val lazyVal = one+ 2
lazyVal: Int = 

scala> lazyVal
res1: Int = 3
Common points for var and val keywords :-
  • We must initialize vals and vars when they are declared
  • Both keywords can be used with constructor parameters. When used as constructor parameters, the mutable or immutable variables specified will be initialized when an object is instantiated.

Function/method declaration:- 

Functions are first class citizen in Scala.To define a function in Scala, use the def keyword followed by the method name, parameters(optional argument lists), optional return type, =, and the method body.The return type of a Scala function is optional because Scala infers the return type of a function automatically, however method parameters type is mandatory.Scala type inference will figure out the type of parameters when you invoke the function but not during the function declaration.Below is syntax for function declaration.In Scala we can also pass a function as a parameter to another function,
def method_name(name: String) : String = {"Body of function"}
scala> def myFunction()= {"Hello, function call!!" }
myFunction: ()String
scala> myFunction()
res6: String = Hello, function call!!
Significance of = in function declaration:- 
1. It separates separate the signature from the method body
2. It communicates Scala compiler to infer the return type of your function. If you omit that, Scala won’t infer your return type.
scala> def myFunction(){"Hello, function call!!" }
:10: warning: a pure expression does nothing in statement position; you may be omitting necessary parentheses
       def myFunction(){"Hello, function call!!" }
                        ^
myFunction: ()Unit
As we can spot the differences, return type of function is displayed as ()Unit, Unit in Scala is equivalent to void in Java.
Nested functions declaration:- Below is sample code shows nested method and it displays count from value passed to 1.
def countTo(n: Int):Unit = {
 def count(i: Int): Unit = {
  if (i <= n) {
   println(i)
    count(i + 1)
   }
 }
 count(1)
}
countTo(5)
Scala provides a shorthand way to create a function in which you write only the function body, called function literals.Function literals are similar to anonymous function in Java.Below example createa list and multiple all element of list using foldRightmethod of List.
scala> val numberList = List(2, 4, 10)
numberList: List[Int] = List(2, 4, 10)

scala> numberList.foldRight(1){(a ,b)=> a*b}
res11: Int = 80

scala> evenNumbers.foldLeft(1) { _ * _ }
res16: Int = 80
Here (a ,b)=> a*b is an function literals, since foldRight method expect a function to passed as an argument.Scala allows us to drop the parameters in anonymous function and only have the method body to make it a function literal and parameters should be replaced with underscores (_).

Aug 23, 2015

How to pretty print JSON using Gson and Jackson

JSON is widely used in web development as data exchange format because of its light weight nature.By default JSON is plain string however JSON looks scary if it is not formatted and in may situation formatted JSON is need for debugging.Here we will see how to format or how to enable pretty printing of JSON in java. If you are using Gson and Jackson then it is very easy to generate pretty print of JSON.

JSON Pretty printing using Gson:- 

Gson has GsonBuilder has instance variable prettyPrinting(Boolean), while creating instance of GsonBuilder using create() method, if prettyPrinting is set true(using setPrettyPrinting() method ) then pretty printing will be enabled and JSON generated will be formatted. Download Gson jar from here and create a java file with following code lines.
Hide code lines
package com.GsonSampleProject.model;

import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class JSONPrettyPrintUsingGson {
  public static void main(String[] args) {
    Map<String, Object> map = new LinkedHashMap<>();
    List<String> skills = new LinkedList<>(
        Arrays.asList("java""python",
        "hadoop"));
    map.put("Name""nikhil");
    map.put("Designation""SSE");
    map.put("skills", skills);
    // Create() method returns an instance of Gson,
    // call toJson() method and prints formatted JSON.
    Gson gObj = new GsonBuilder().setPrettyPrinting().create();
    System.out.println(gObj.toJson(map));
   
  }
}
Here we have created a map(object of JSON) and added a list (array of JSON) as part of it. Whne we execute JSON is pretty printed. Similarly , we can have any POJO(Plain old java object) in-place of map and outcome is pretty printed.   

JSON Pretty printing using Jackson:- 

Download jackson-all-1.9.0.jar. Create a java class and use following code lines.
Hide code lines
package com.GsonSampleProject.model;

import java.io.IOException;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.ObjectWriter;
import org.codehaus.jackson.map.SerializationConfig;

public class JSONFormattedWithJackson {
  public static void main(String[] args) {
    Map<String, Object> map = new LinkedHashMap<>();
    List<String> skills = new LinkedList<>(Arrays.asList("java""python",
        "hadoop"));
    map.put("Name""nikhil");
    map.put("Designation""SSE");
    map.put("skills", skills);
    String jsonString = "[{\"Name\":\"Nikhil\",\"skills\":[\"java\","
        "\"python\",\"Hadoop\"],\"Address\":\"Hyderabd\"},"
        "{\"Name\":\"Ranjan\",\"skills\":[\"java\","
        "\"python\",\"NoSQL\"],\"Address\":\"Hyderabd\"}]";
    ObjectMapper mapper = new ObjectMapper();
    try {
      System.out.println("==========Option 1===========");
      // 1. String to Formatted JSON conversion
      Object jsonObjet = mapper.readValue(jsonString, Object.class);
      // for Jackson 1.x only use
      ObjectWriter writer = mapper.defaultPrettyPrintingWriter();
      // for jackson 2.x use following
      // ObjectWriter writer = mapper.writer().withDefaultPrettyPrinter();
      String indentedResult1 = writer.writeValueAsString(jsonObjet);
      System.out.println(indentedResult1);
      //2. Object to formatted JSON conversion
      String indentedResult2 = writer.writeValueAsString(map);
      System.out.println(indentedResult2);
      
      System.out.println("==========Option 2===========");
      // Object to Formatted JSON conversion
      mapper.enable(SerializationConfig.Feature.INDENT_OUTPUT);
      System.out.println(mapper.writeValueAsString(map));
    catch (JsonParseException e) {
      e.printStackTrace();
    catch (JsonMappingException e) {
      e.printStackTrace();
    catch (IOException e) {
      e.printStackTrace();
    }

  }
}
Here we have multiple option to convert String/Object into pretty print format. In option 1, we  created mapper instance of ObjectMapper and mapper instance have readValue method that read input(FIle, InputStream,String or Object) and with writeValueAsString() method it displays formatted output.Please note difference mentioned for 1.x and 2.x. Do not use defaultPrettyPrintingWriter() ,it has been deprecated instead prefer to use Option 2. In second option, we enable properties in mapper for "INDENT_OUTPUT", so by default if object is printed it will be pretty printed.

Read also:
How to convert JSON to Object and Object to JSON using Google Gson.

Aug 22, 2015

How to convert JSON to Object and Object to JSON using Google Gson

In previous post we learned How to parse/encode-decode JSON using JSON.simple.JSON is known for its light weight data exchange format. In web centric application integrated with Object oriented infrastructure, their will be high volume of data exchange and data are sent in form of JSON over wires.So, how do we convert (serialize) object to JSON and retrieve that object to JSON(deserialize). The main agenda of this post is understand serialization and de-serialization using GSON- an open source java library for converting Java Objects into their JSON and from JSON to java Objects. Some important features of GSON:
  • Gson has extensive support for java generics.Gson can be used to convert complex hierarchy of connected object model into JSON and vice versa.
  • Gson can work with arbitrary Java objects including pre-existing objects whose source code we cannot modify.Gson can also be used to convert third party object into JSON.
Remember, sample code speaks louder than raw text. Lets setup development environment, first download the required jar or configure maven dependency.
1. Gson jar can be downloaded from here
2. Maven dependency : Add following dependency in pom.xml
   <dependency>
       <groupId>com.google.code.gson</groupId>
       <artifactId>gson</artifactId>
       <version>1.7.1</version>
   </dependency>

Java Object to JSON using Gson

 Create a java project and add download jar in class path/add dependency in pom.xml, if maven project. Create a POJO Employee.java, we will create employee list and convert it into JSON. Create a Employee.java  with following code lines: Here we have two level of class hierarchy - connected object model (SalaryComponents inside Employee).
Hide code lines
package com.devinline.model;

/**
 
 @author nikhil
 */
public class Employee {
  private String employeeName;
  private String employeeId;
  private String designation;
  private SalaryComponents salaryComponent;
  private String takeHomeSalary;

  public String getTakeHomeSalary() {
    return takeHomeSalary;
  }

  public void setTakeHomeSalary(String takeHomeSalary) {
    this.takeHomeSalary = takeHomeSalary;
  }

  public Employee() {

  }

  public Employee(String employeeName, String employeeId, 
      String designation,
      SalaryComponents salaryComponent) {
    super();
    this.employeeName = employeeName;
    this.employeeId = employeeId;
    this.designation = designation;
    this.salaryComponent = salaryComponent;
  }

  public void setsalaryComponent(SalaryComponents 
      salaryComponent) {
    this.salaryComponent = salaryComponent;
  }

  public String getEmployeeName() {
    return employeeName;
  }

  public void setEmployeeName(String employeeName) {
    this.employeeName = employeeName;
  }

  public String getEmployeeId() {
    return employeeId;
  }

  public void setEmployeeId(String employeeId) {
    this.employeeId = employeeId;
  }

  public String getDesignation() {
    return designation;
  }

  public void setDesignation(String designation) {
    this.designation = designation;
  }

  public SalaryComponents getsalaryComponent() {
    return salaryComponent;
  }

  public static class SalaryComponents {
    private int basicSalary;
    private int hra;
    private int pfDeduction;
    private int spclAllowance;

    public SalaryComponents(int basicSalary, int hra, 
        int pfDeduction,
        int spclAllowance) {
      super();
      this.basicSalary = basicSalary;
      this.hra = hra;
      this.pfDeduction = pfDeduction;
      this.spclAllowance = spclAllowance;
    }

    public int getBasicSalary() {
      return basicSalary;
    }

    public void setBasicSalary(int basicSalary) {
      this.basicSalary = basicSalary;
    }

    public int getHra() {
      return hra;
    }

    public void setHra(int hra) {
      this.hra = hra;
    }

    public int getPfDeduction() {
      return pfDeduction;
    }

    public void setPfDeduction(int pfDeduction) {
      this.pfDeduction = pfDeduction;
    }

    public int getSpclAllowance() {
      return spclAllowance;
    }

    public void setSpclAllowance(int spclAllowance) {
      this.spclAllowance = spclAllowance;
    }

  }
}
Now we will create our processing unit ,SerialDeserialUsinGson.java with following code lines. Here we have created Gson object (using default constructor with default values).We can create Gson object with various customization like changing fields name, allow serialization of nulls by passing boolean value(by default nulls are serialized). We will revisit this advanced concept later. As of now use default values of Gson class.
Hide code lines
package com.sample.json;

import java.util.LinkedList;

import com.devinline.model.Employee;
import com.devinline.model.Employee.SalaryComponents;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class SerialDeserialUsinGson {

 public static void main(String[] args) {
  LinkedList<Employee> empList = new LinkedList<>();
  // Create two Employee object and add to empList
  for (int i = 0; i < 2; i++) {
    empList.add(new Employee("Nikhil" + i, "007" 1
      "SE" + i,
          new SalaryComponents(1000 * i, 800 * i,
         300 * i,
           200 * i)));
  }
  // Create Gson Object using default values
  Gson gsonObj = new Gson();
  String employeesJSON = gsonObj.toJson(empList);
  System.out.println(employeesJSON);// display compact JSON
  /*System.out.println(new GsonBuilder().setPrettyPrinting().
      create().toJson(empList));*/
 }

}
Let's walk thorough the above code, first we created two employee object via for loop(Scary code☺) just ignore the logic.Next we created Gson object and used toJson method of Gson class to convert employee List into JSON structure.Run above program and see the output, we will get compact JSON structure.Now uncomment last line of the code and run it again. This time outcome is formatted and prettyprint JSON is displayed on console. For more details How to pretty print JSON in java ?


Textual description of firstImageUrl

JSON parsing in java - JSON endoding and decoding in java


In previous post we discussed JSON is future of web centric application development . JSON is future, so better learn it and use it seamlessly in development process.The main agenda of this post is learn how do we process JSON document(Read and write operation in JSON) in java. As we know JSON is subset of javaScript so javaScript has inbuilt support for parsing JSON. In javascript we can parse JSON like this:
var employeeArray = '{ "employees" : [' +
'{ "firstName":"Nikhl" , "lastName":"ranjan" },' +
'{ "firstName":"Rakesh" , "lastName":"Jha" },' +
'{ "firstName":"Rahul" , "lastName":"jain" } ]}';

var employeesObject = JSON.parse(employeeArray); 
employeesObject.employees[1].firstName //It displays Rakesh(0 index base array)
However, other language like java, python.etc either has to provide inbuilt support for it as part of the language or uses third party library for it. Java 7 has package "javax.json" which provides an object model API to process JSON. i.e: It provides inbuilt support for JSON parsing and object creation. JSON parsing using java 7 javax.json interface has been discussed here.
There are various third party library(jars) available for JSON parsing/decoding in java, which jars we should use depends on what we want to do with JSON - just read the attribute values or map JSON to some Model class. We will start with how to do encoding/decoding using JSON.simple followed by use of GSON and Jackson
Lets create a Json file input.json and do copy/paste following in it.We will do processing of this json in following section.
Hide code lines
{
  "employees":[
    {
      "employeeName":"Nikhil",
      "Designation":"SE",
      "empId":"101",
      "salaryComponent":[
        {
          "baseSalary":"1000",
          "hra":"300",
          "pfDeduct":"200",
          "spclAllowance":"3000"
        }
      ],
      "takeHomeSal":"4100"
    },
    {
      "employeeName":"Ranjan",
      "Designation":"SSE",
      "empId":"102",
      "salaryComponent":[
        {
          "baseSalary":"2000",
          "hra":"300",
          "pfDeduct":"200",
          "spclAllowance":"4000"
        }
      ],
      "takeHomeSal":"6100"
    }
  ]
} 

1. JSON.simple(org.json.simple):- 

JSON.simple is a simple Java toolkit for JSON. It has full support for encoding or decoding JSON text.There is a direct mapping between JSON data types(string, boolean, number, null, array and object) and Java entities like(java.lang.String, java.lang.Number, etc).JSON array is mapped to java.util.List and object is mapped to java.util.Map.Here is complete list of mapping and other features related to JSON.simple.
Download org.json.simple jar from here and place downloaded jar in class path or if you are using any IDE like eclipse create a java project and go to Build path and add this downloaded jar as external jar.Create a java file and do copy/paste following sample code lines.
Parsing/decoding of JSON:-
Hide code lines
package com.sample.json;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class JSONParsing {

public static void main(String[] args) {
 String employeeString = "{\"name\": \"Nikhil\",\"Organization\":"
   + "\"xyz\",\"skills\":\"Java\"}";
 // 1. Parse Input string and display Organization name of nikhil
 readStringAndParse(employeeString);
 // 2. Parse Input file and display employee name of first employee
 readInputFileAndParse();
}

public static void readStringAndParse(String employeeString) {
 JSONObject jsonObject = (JSONObject) JSONValue.parse(employeeString);
 // Check whether jsonObject contains key "Organization"
 if (jsonObject.containsKey("skills")) { // Get Organization value
  System.out.println(jsonObject.get("Organization"));
 }
}

public static void readInputFileAndParse() {
 // Read input file from resources folder.
 ClassLoader classLoader = JSONParsing.class.getClassLoader();
 File inputFile = new File(classLoader.getResource(
   "resources/input.json").getFile());
 // Create JSON parser Object
 JSONParser parser = new JSONParser();
 Object obj;
 try {
  // parse input file
  obj = parser.parse(new FileReader(inputFile));
  // Type cast Object into JSONObject
  JSONObject inputTestDataObject = (JSONObject) obj;
  // get employees array from JSONObject
  JSONArray empList = (JSONArray) inputTestDataObject
    .get("employees");
  // Display employeeName of first Object- get(0)
  System.out.println(((JSONObject) empList.get(0))
    .get("employeeName"));
 } catch (IOException | ParseException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 }
}

}
Sample output: Execute above program and you should see following in your console.
-----------------------------------
xyz
Nikhil
-----------------------------------
Lets walk through the code, method readStringAndParse(String ) creates JSONObject using JSONValue.parse(String). JSONObject behaves as java Map and using get(key) we display organization name.Similarly , in readInputFileAndParse() we read input file present in resource folder and instead of using JSONValue here we are creating object of JSONParser and pareses input file. From JSONObject we get employees array using get(key) and refer to first object of array(imagine java List) using get(index) and finally from that object we retrieve employeeName.Please go through the code once more and see the structure of JSON. it's JSON structure which drives how to parse JSON. Sample code related to advance features of JSON.simple like Container factory and SAX-like content handler can be find here.   
Creating JSON/Encoding of JSON:-
Encoding of JSON means we will create JSON object/stream and similar to wthat we read from input file while parsing. Let's create a new method inside above class and copy/paste following code.
Hide code lines
public static void encodeJSONUnordered() {
  JSONObject empObj = new JSONObject();
  empObj.put("employeeName", "Nikhil");
  empObj.put("Designation", "SSE");
  empObj.put("empId", new Integer(1000));
  
  //Create salary Object and add key/values
  JSONObject salObject = new JSONObject();
  salObject.put("baseSalary", new Double(1000));
  salObject.put("hra", new Double(300));
  salObject.put("pfDeduct", new Double(200));
  salObject.put("spclAllowance", new Double(3000));
  
  //Salary component as array, add salObj in it
  JSONArray salList = new JSONArray();
  salList.add(salObject);
  
  //add salList to main
  empObj.put("salaryComponent", salList);
  
  //last key/value entry of employeeObject
  empObj.put("takeHomeSal", new Double(200));
  
  //Create an employeeArray and
  //Add employee Object in it
  JSONArray employeeArray = new JSONArray();
  employeeArray.add(empObj);
  
  //Outcome is unOrdered,
  //order of key/value is not preserved.
  System.out.println("{\"employees\":"+employeeArray + "}");
 }
Here we are trying to create "employees" JSON structure mentioned above. As we know JSONObject is mapped to java.util.map and JSONArray is mapped to java.util.list, keep these two thing in mind  try to create object(map) and array(list) and add them as per JSON doc structure. In above sample code, first we created an empObj(It is java map) and added name, designation and id as key directly to it. This empObj contains an array(java List) and in turn JSONobjct is element of this list. so create an salobject and add key/value pairs and add this salObj(map) to salList. And finally, add this salList to empObject. Now we created and employee.
Sample output:- When you call this method from main() ,you will get this in console:
--------------------------------------------------------------------------------------------9999999999
{"employees":[{"takeHomeSal":200.0,"empId":1000,"salaryComponent":[{"pfDeduct":200.0,"baseSalary":1000.0,"spclAllowance":3000.0,"hra":300.0}],"Designation":"SSE","employeeName":"Nikhil"}]}
----------------------------------------------------------------------------------------------
We can easily spot from sample output that order of insertion not retained, reason is obvious. JSONObject (mapped to java map and java map does not maintain order of element).
How do we maintain order of insertion in JSON?
For doing this we have to use java LinkedHashMap, since it maintains order of element insertion.Create a new method and copy/paste below code in it and verify the differences in sample output:
Hide code lines
public static void encodeJSONOrdered() {
  LinkedHashMap<String, Object> mapOrdered = 
    new LinkedHashMap<>();
  mapOrdered.put("employeeName", "Nikhil");
  mapOrdered.put("Designation", "SSE");
  mapOrdered.put("empId", new Integer(1000));
  JSONValue.toJSONString(mapOrdered);
  // Create salary Object and add key/values
  JSONObject salObject = new JSONObject();
  salObject.put("baseSalary", new Double(1000));
  salObject.put("hra", new Double(300));
  salObject.put("pfDeduct", new Double(200));
  salObject.put("spclAllowance", new Double(3000));

  // Salary component as array, add salObj in it
  JSONArray salList = new JSONArray();
  salList.add(salObject);

  // add salList to main
  mapOrdered.put("salaryComponent", salList);

  // last key/value entry of employeeObject
  mapOrdered.put("takeHomeSal", new Double(200));

  // Create an employeeArray and
  // Add employee Object in it
  JSONArray employeeArray = new JSONArray();
  employeeArray.add(mapOrdered);
  String output ="{employees:"+employeeArray + "}";
  
  // Outcome is Ordered,
  // order of key/value is preserved.
  System.out.println(output);
 }
LinkedHashMap has been used in this method to maintain insertion order.LinkedHashMap maintains a linked-list to store the elements and maintain sequence of insertion. Read How does LlinkedHashMap works internally?.
Sample Output: When we execute above method from main we notice that order of insertion is maintained.
---------------------------------------------------------
{"employees":[{"employeeName":"Nikhil","Designation":"SSE","empId":1000,"salaryComponent":[{"pfDeduct":200.0,"baseSalary":1000.0,"spclAllowance":3000.0,"hra":300.0}],"takeHomeSal":200.0}]}
---------------------------------------------------------
JSON object/array can also be streamed using StringWriter (concrete implementation that uses a StringBuilder/string). Here is the sample code for that.
JSONObject obj = new JSONObject();
......fill that object
StringWriter out = new StringWriter();
obj.writeJSONString(out); //SOP(obj) will display JSON.
For more JSON encoding sample code refer this. In next post we will see how to use google GSON and Jackson for JSON serialisation / de-serialisation (map JSON with model class).
Next: JSON- serialisation / de-serialisation with GSON and Jackson

Software system supporting XML and JSON

In previous post, we saw why JSON is trending in town when we need to choose between JSON and XML as data interchange format. However, XML is preferred when document presentation and mixed data representation become priority. Here we will list down software system /web architecture- API's which are using XML and JSON.
Type Software system/API's
Desktop software uses XML only
  1. Microsoft Word
  2. Apache OpenOffice
  3. LibreOffice.
Notes: XML is obvious choice here because it has support of storing mixed content naturally and the major task associated with these software are creating document, editing and styling at same time. An user can edit and style both same time and such information can be stored in xml naturally.
Databases supporting XML
  1. IBM DB2
  2. Microsoft SQL Server
  3. Oracle Database
  4. PostgresSQL
  5. BaseX
  6. eXistDB
  7. MarkLogic
  8. MySQL
Databases supporting XML
  1. MongoDB
  2. CouchDB
  3. eXistDB
  4. Elastisearch
  5. BaseX
  6. OrientDB
  7. MarkLogic
  8. PostgresSQL
  9. Riak
  10. Oracle Database
Notes: JSON is obvious choice of NoSQL database like MongoDB, CouchDB because they store data in JSON format. However, relational database like Oracle, PostgresSQL are also supporting JSON. Like JSON is future as data exchange format, NoSQL is future too in database technologies.
Major public APIs uses JSON only
  1. Facebook Graph API
  2. Google Maps API
  3. Twitter API
  4. AccuWeather API
  5. Pinterest API
  6. Reddit API
  7. Foursquare API
Notes: Facebook and Google Map is dealing with high volume of data in range of GB or PetaBytes, so JSON will be most efficient data transmission format. 
Major public APIs uses XML only Amazon Product Advertising API.
Major public APIs uses JSON and XML both
  1. Google Cloud Storage
  2. Linkedin API
  3. Flickr API
Volume of data is high : JSON preferred
Focus on presentation/document   : XML is preferred. 
  
Read also : Why JSON is future of web centric development?


Reference : XML vs  JSON
Textual description of firstImageUrl

Why JSON is future of web centric development - Tug of war(XML vs JSON)

XML(Extensible Markup Language) and JSON(javaSctipt object notation) are the two most commonly used formats for data exchange/interchange over wires/internet or as data-source/ configuration file. XML is an old player() and JSON joined the show later. JSON is getting popularity and industries extensively using web-service are moving from XML to JSON. Does it mean Does XML is getting obsolete? or JSON is pushing XML and moving ahead?. Answer to this question is Yes and No both.
Yes, because JSON is lightweight(less bandwidth intensive) and data oriented, so it's popularity is increasing and industries are preferring it over XML. And same time No, because there are some who still use XML because of it document oriented and schema focussed features. JSON is absolutely not superior to the XML every where,it is use-case dependent.However We have to say loudly and admit it JSON has an edge over XML.
All major "Amazon Product Advertising API" uses only XML and at the same time Facebook Graph API, Google Maps API, Twitter API, AccuWeather API, Pinterest API, Reddit API, Foursquare API uses JSON.
It has been long, over the years developer community divided over XML and JSON and it is still on with compromising logic, neither JSON and XML is superior over each other,it is the use case which drive organization to select JSON or XML.Remember a decade ago, XML was the hero of the town(first choice of data interchange format) and it eliminated all the shortcomings of SGML(Standard Generalized Markup Language) and played a vital role in evolution of web.But now JSON is dominating this data centric world and all major players extensively using it as privileged data format.

Why JSON is becoming more popular and organization first choice for data exchange?
Advantage of JSON over XML:-

If Facebook, Google ,Twitter and Foursquare is using JSON , then I do not think there is an iota of doubt about JSON feature richness over XML.What we need to understand what makes JSON so adorable when it comes to exchanging data over internet.
  1. JSON less verbose than XML: JSON documents are very straight forward and it is data focused instead of  document oriented(XML documents). No extra ceremony is required other than { }( braces ) for objects , [ ] (brackets) for array and :(colon ) to separate key/value pair.However , XML requires little decoration to make a valid XML documents. It causes variation in size of the JSON document and XML document and in turn XML documents are more bandwidth intensive compared to JSON documents.So , transmission of JSON doc is faster compared to XML document. See below diagram to differentiate between XML and JSON doc. JSON doc is clearly light weight and less verbose than XML doc.
JSON Document sample XML Document sample
{  "firstname" : "Nikhil",
   "lastname" : "Ranjan"
   "employeeId": "007"
   "designation": "SSE"
   "Organization": "XYZ"
   "skills":["java":"8/10","javaSctipt":"6                /10","python":"5/10"]
}
<Employee>
   <firstname>Nikhil</firstname>
   <lastname>Ranjan</lastname>
   <employeeId>007</employeeId>
   <designation>SSE</designation>
   <Organization>XYZ</organization>
   <skills>
      <java>8/10</java>
      <javaScript>6/10</javaSctipt>
      <python>6/10</python>
   </skills>
</Employee>
  1. JSON processing is faster than XML document: Apart from small JSON document compared to XML document for same data, it has been found that processing speed of JSON document is faster than XML document. JSON is estimated to parse up to one hundred times faster than XML.Along with processing , serialization and deserialization of JSON can be performed efficiently than XML document.
  2. Less System CPU resource utilization: In terms of CPU utilization, experiment conducted by Nurzhan, Michael ,Randall and Clemente suggest that JSON document takes less system CPU resource than XML document. It states that , JSON document takes more user CPU and less system CPU and overall resource consumption is less in JSON document. More user CPU time is better because it makes less system call and so less system CPU utilization. See below diagram for broader picture regarding transmission time and CPU utilization:
Transmission and CPU utilization analysis: XML vs JSON (Source: A Case Study by Nurzhan)
  1. Natural support of data structure: JSON doc implicitly uses { } for object and [ ] for array
    and it helps it to map directly to the corresponding data structures in various other languages. Another important feature that makes it compatible with Object oriented environment is that namespace of each fields is resolved in Object scope independently. Some people see JSON as deficient in namespace resolution. 
  2. JSON parsing support for all well known high level language : JSON is subset of JavaScript. JSON works seamlessly not only with JavaScript but also with Java, Python, C++, etc. There are various tools and third party library available to support JSON parsing efficiently. For java we have Gson, Genson, Jackson and FlexJson. Read how to do JSON parsing in java here.
These are the significant features of JSON which makes it popular and preferred data exchange language.So,where ever there is need of transmission of data in bulk over wires , JSON is preferred. Now lets see what are the areas where JSON is making its presence these days.
  • NoSQL and Big data: In this Web-centic world high volume of data (Google Map, Airlines info, etc) is transmitted over wires, so it was inevitable to opt some data transmission format which will be efficient and less bandwidth intensive.The most popular NoSQL databases like MongoDB and CouchDB relied on JSON as most preferred data transmission format and JSON playing key role in dealing with high volume of data efficiently. Along with these NoSQL
    databases Amazon’s DynamoDB architecture is entirely based on REST/JSON and HBase(part of hadoop ecosystem) is mostly inclined towards JSON.
  • REST popularity as data transfer protocol:  SOAP is XML based well known data transfer protocol. However, SOAP is very bulky and industries is shifting towards REST for exposing most of the resources(except sending some confidential data) and JSON has played a crucial role to make REST as industries first preference over SOAP. With popularity of REST many organization like Twitter and ForSquare has shifted their API base to support JSON only.Some are supporting both XML and JSON so as their major APIs like Google Cloud Storage, Linkedin API, Flickr API. Here is the complete list of software/web system using XML/JSON.
  • Internet of things- Support for non computer device: It is expected that by 2020 the number of devices operable will explode from 20 million to 260 million and most of these devices will be using embedded system.Here lightweight JSON will be undisputed winner over XML.Future of JSON is bright.
  • Ubiquitous JavaScript : Days are gone when javaScript was considered as front end scripting language. With evolution of javaScript in the form of Node.js (a server-side JavaScript framework), full stack development with javaScript became a very possible and it is highly compatible with JSON(Remember JSON is javaScript subset). With Node.js and MongoDB, it is very possible to create a light weight application and serve to wide range to device. JSON data interchange format has Ecma standards blessing too so it is also motivating Web application development community to adopt JSON as data exchange format.
The "JSON" is future, when we think in terms of serving wide range of application and supporting or different types of language. Lets summarize it in one line: JSON will be first preference for data exchange.
Remember XML is not dead , So how do we appreciate XML in terms of its use ?
XML is document oriented (JSON is data oriented ) and XML makes its presence when we need represent document by giving semantic meaning to text through its tree-like structure.
 and XML has natural ability to represent mixed content (JSON does not have it , however it can be achieved).

Read also:
  1. JSON parsing in java - encoding and decoding JSON
  2. List of software system using JSON and XML
References:
1.Comparison of JSON and XML Data Interchange Formats: A Case Study
2. A debate : XML vs JSON