Encoding JSON In Java With Simple Example

By Faruque Ahamed Mollick

In this article, I am going to tell you how to encode JSON objects using Java programming language with simple example code. I hope you will enjoy this tutorial.

At first, you need to prepare the environment for this tutorial. Before you start writing code and encoding using Java, you need to install a JSON module. In this tutorial, I am going to use  JSON.simple. Now need to be added the location of json-simple-1.1.1.jar file to the environment variable CLASSPATH.

Encoding JSON in Java

Following is a simple example of encoding a JSON object using Java JSONObject. JSONObject is a subclass of java.util.HashMap.

Below is the given Java code:

import org.json.simple.JSONObject;

class JsonEncodeExample {

   public static void main(String[] args){
      JSONObject obj = new JSONObject();

      obj.put("name", "Jone");
      obj.put("phone_number", new Integer(4578356945));
      obj.put("balance", new Double(155.62));
      obj.put("is_present", new Boolean(true));

      System.out.print(obj);
   }
}

After compiling and executing the above java program it will return the output result that is given below:

{"balance": 155.62, "phone_number":5269873622, "is_present":true, "name":"Jone"}

I am going to give you another example which will show a JSON object streaming using Java JSONObject. below is the Java code:

import org.json.simple.JSONObject;

class ExampleJsonDemo {

   public static void main(String[] args){
  
      JSONObject obj = new JSONObject();

      obj.put("name","Jone");
      obj.put("phone_number",new Integer(5269873622));
      obj.put("balance",new Double(155.62));
      obj.put("is_present",new Boolean(true));

      StringWriter out = new StringWriter();
      obj.writeJSONString(out);
      
      String jsonText = out.toString();
      System.out.print(jsonText);
   }
}

And the output result of above code after compiling and executing will be:

{"balance": , "phone_number":5269873622, "is_present":true, "name":"Jone"}

Leave a Reply

Your email address will not be published. Required fields are marked *