Encoding and Decoding of Json Objects Through Java

As you know JSON can be used with many programming languages, it is popularly used with Java, PHP, and Python as well. In this tutorial, you will learn about the encoding and decoding of JSON objects through Java. So, let us dig deep into it.

Encoding JSON with Java

Encoding of JSON object in a Java program is possible using JSONObject that is a subclass of java.util.HashMap. By default, no order is set. To set a strict element's ordering, the JSONValue.toString() method is used. Let us see a program which shows the basic encoding of JSON data through Java. For using this JSON with Java, you have to implement this jar file: json-simple-1.1.1.jar. Moreover, the JSON.simple is used for mapping values from the left-hand side to the right-hand side at the time of decoding or parsing and the reverse at the time of encoding.

Example:
import org.json.simple.JSONObject;

class JsonwithJava {
 public static void main(String argu[]) {
  JSONObject o1 = new JSONObject();
  o1.put("name", "Alex");
  o1.put("roll", new Integer(12));
  o1.put("total_marks", new Double(684.50));
  obj.put("pass", new Boolean(true));
  System.out.print(o1);
 }
}

When you compile and execute the program mentioned above, the output will be:

Output:
{"name":"Alex", "balance": 648.50, "roll":12, "pass":true}

Decoding JSON Data through Java

Here is a simple program showing the decoding of JSON in the Java program.

Example:
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

public class JsonDecodeExample1 {
 public static void main(String[] args) {
  String s = "{\"name\":\"Alex\",\"marks\":648.50,\"roll\":12}";
  Object o1 = JSONValue.parse(s);
  JSONObject jsonObj = (JSONObject) o1;
  String name = (String) jsonObj.get("name");
  double marks = (Double) jsonObj.get("marks");
  Integer roll = (Integer) jsonObj.get("roll");
  System.out.println(name + " " + marks + " " + roll);
 }
}

Executing the above program will give output as:

Output:
Alex  648.50            12