As you know, JSON can be used with many programming languages; it is popularly used with Java, PHP, and Python. 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 a 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 that 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.


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));

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


{"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.


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:


Alex  648.50            12

Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram