This section describes how to encode/decode JSON in Java. We can process JSON using Java if and only if one of the JSON modules is present and added into the CLASSPATH. So ensure, you have latest jar file for JSON in your machine and its path added to the environment variable CLASSPATH.
Further, JSON types are mapped to JAV types in JSON.simple file. JSON string is mapped to java.lang.String; JSON number is mapped to java.lang.Number; JSON boolean (true|false) is mapped to java.lang.Boolean; JSON null is mapped to null; JSON array is mapped to java.util.List and JSON objectis equivalent to java.util.Map.
Let us see how JSON is encoded and decoded in Java.
import org.json.simple.JSONObject;
class JsonEncodeDemo {
public static void main(String[] args) {
JSONObject studentobj = new JSONObject();
studentobj.put("fname", "Kanav");
studentobj.put("lname", "Bhargava");
studentobj.put("age", new Integer(11));
studentobj.put("grade", new Integer (6));
studentobj.put("percentage",new Double(95.2));
studentobj.put("isBoy", new Boolean(true));
System.out.print(studentobj);
}
}
Once you compiler and run, you get the following output
{"age": 11, "fname": "Kanav", "grade": 6, "isBoy": true, "lname": "Bhargava", "percentage": 95.2}
Now let us write a simple program showing the decoding of JSON in the Java program.
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
public class JsonDecodeExample1 {
public static void main(String[] args) {
String s = "{\"name\":\"Nikunj\",\"percentage\":95.50,\"roll\":141}";
Object obj = JSONValue.parse(s);
JSONObject jsonObj = (JSONObject) obj;
String name = (String) jsonObj.get("name");
double perc = (Double) jsonObj.get("percentage");
Integer roll = (Integer) jsonObj.get("roll");
System.out.println(name + " " + marks + " " + roll);
}
}
This code will output
Nikunj 95.5 141