Blog about Programming Languages & Coding

Blog about Programming Languages & Coding
Contents for Computer Science, IT, B.Sc. CS & IT, M.Sc. CS & IT, MCA, BE CS & IT, ME CS & IT , Interview Questions, Books and Online Course Recommendations from Udemy, Coursera, etc

Encoding and Decoding JSON in Java

JSON ProgramsI( Encoding and Decoding in Java)

JSON ProgramsI( Encoding and Decoding in Java)

Encoding JSON in Java


Following is a simple example to encode a JSON object using Java JSONObject which is a subclass of java.util.HashMap. No ordering is provided. If you need the strict ordering of elements, use JSONValue.toJSONString ( map ) method with ordered map implementation such as java.util.LinkedHashMap.

 

import org.json.simple.JSONObject;

class JsonEncodeDemo {

    public static void main(String[] args){

      JSONObject obj = new JSONObject();

       obj.put("name", "compsciflix");

      obj.put("num", new Integer(100));

      obj.put("balance", new Double(2000.58));

      obj.put("is_vip", new Boolean(true));

       System.out.print(obj);

   }

}

On compiling and executing the above program the following result will be generated −

{"balance": 2000.58, "num":100, "is_vip":true, "name":"compsciflix"}


Following is another example that shows a JSON object streaming using Java JSONObject −

import org.json.simple.JSONObject;

 

class JsonEncodeDemo {

 

   public static void main(String[] args){

      JSONObject obj = new JSONObject();

 

      obj.put("name","compsciflix");

      obj.put("num",new Integer(100));

      obj.put("balance",new Double(1000.1));

      obj.put("is_vip",new Boolean(true));

 

      StringWriter out = new StringWriter();

      obj.writeJSONString(out);

      

      String jsonText = out.toString();

      System.out.print(jsonText);

   }

}

On compiling and executing the above program, the following result is generated −

{"balance": 1000.1, "num":100, "is_vip":true, "name":"compsciflix"}








Encoding and Decoding JSON in Java Encoding and Decoding JSON in Java Reviewed by Asst. Prof. Sunita Rai on March 27, 2022 Rating: 5

No comments:

Powered by Blogger.