Friday, November 2, 2012

Convert an object to json string and vice versa in Java and Javascript

Today we will see how to convert an object to json string and vice versa. An object could be JSONObject or any Java Object for example Map of list, List of map etc. Also please see my earlier post on Java Examples for JSON encoding, click here.

Note - To run below examples you need to include json-simple-1.1.1.jar in classpath. Download the JAR file from http://code.google.com/p/json-simple/

Example 1 : Convert JSONObject to JSON String and vice versa

Output :

{"Name":"Ramesh","Nickname":null,"Salary":15000.0,"isPermanent":true,"EmployeeId":121}
121
Ramesh
15000.0
true
null

Example 2 : Convert Java Object to JSON String and vice versa

Output :

{"India":["Mumbai","Delhi","kolkata"]}
["Mumbai","Delhi","kolkata"]


In above example you have seen how to convert object to json string and vice versa in Java however many times you may need to do same in Javascript. For doing the same in Javascript you have below methods

1. Convert Object to Json string

var objStr = JSON.stringify(obj);

2. Convert Json string to Object

var obj = JSON.parse(objStr);


Note: For javascript you may get error 'JSON' is undefined in IE, to resolve it download json2.js from below link and add to your file.
https://github.com/douglascrockford/JSON-js

Syntax :