7 May 2015

JSON library Usage

JSON Library usage for replacing the value of particular key in JSON object.


JSONObject: JSONObject is an unordered collection of key value pairs.

Ex:{
         "Employee1": {"Name":"John", "EmpId":"1002", "Address":"California" }
         "Employee2": {"Name":"Alex", "EmpId":"1001", "Address":"Mexico" }
         "Employee3": {"Name":"Luci", "EmpId":"1003", "Address":"New york" }
     }

With the above JSONString create a JSONObject.

String strEmployees ="{
         \"Employee1\": {\"Name\":\"John\", \"EmpId\":\"1002\", \"Address\":\"California\" },
         \"Employee2\": {\"Name\":\"Alex\", \"EmpId\":\"1001\", \"Address\":\"Mexico\" },
         \"Employee3\": {\"Name\":\"Luci\", \"EmpId\":\"1003\",\"Address\":\"New york\" }
     }";

JSONObject employess = new JSONObject(strEmployees);

To replace the details of "Employee1" in the above JSONString, use the JSONObject employees and method put with key value pair, which replaces if the key is already present in the JSON, otherwise it puts the new entry into the JSONObject.

System.out.println(employees.getJSONObject("Employee1"));

Output:

{"Name":"John", "EmpId":"1002", "Address":"California" }

Now to change Employee1 to {"Name":"Stacy", "EmpId":"1005", "Address":"Texos" }

Create a new JSONObject with the above details.

JSONObject employee1 = new JSONObject("{\"Name\":\"Stacy\", \"EmpId\":\"1005\", \"Address\":\"Texos\" }");

employees.put("Employee1", employee1);

Now print the output of employee1

System.out.println(employees.getJSONObject("Employee1"));

The output will be as below.

 {"Name":"Stacy", "EmpId":"1005", "Address":"Texos" }