The org.json.simple library allows us to read and write JSON data in Java. In other words, we can encode and decode the JSON object. The org.json.simple package contains important classes like JSONValue, JSONObject, JSONArray, JsonString and JsonNumber. We need to install the json-simple.jar file to execute a JSON program whereas org.json library has classes to parse JSON for Java. It also converts between JSON and XML, HTTP header, Cookies, and CDF. The org.json package contains important classes like JSONObject, JSONTokener, JSONWriter, JSONArray, CDL, Cookie and CookieList. We need to install the json.jar file to execute a JSON program.
Example for org.simple.json package
import org.json.simple.JSONObject; public class SimpleJsonTest { public static void main(String[] args) { JSONObject jsonObj = new JSONObject(); jsonObj.put("empName", "Raja"); jsonObj.put("employeeId", "115"); jsonObj.put("age","30"); System.out.println(jsonObj.toJSONString()); } }
Output
{"empName":"Raja","employeeId":"115","age":"30"}
Example for org.json package
import org.json.*; public class JSONTest { public static void main(String args[]) throws JSONException { String json = "{" + "Name : Jai," + "Age : 25, " + "Salary: 25000.00 " + "}"; JSONObject jsonObj = new JSONObject(json); System.out.println(jsonObj.toString()); } }
Output
{"Salary":25000,"Age":25,"Name":"Jai"}