• Register

This section covers how to convert json obj into string .Let us commence with making the atmosphere to commence our programming with Java for JSON.

Environment

Beforehand you commence with conversion, JSON using Java, you must to install any of the JSON units existing. For this lesson we have downloaded and installed JSON.simple and have added the site of json-simple-1.1.1.jar file to the environment var CLASSPATH.

Plotting between JSON and Java entities

JSON.simple maps objects from the left side to the right side while conversion or parsing, and maps objects from the right to the left while encoding.
Converting  JSON to String in JavaOn conversion, the real class of java.util.List is org.json.simple.JSONArray and the real  class of java.util.Map is org.json.simple.JSONObject.

Subsequent is a artless sample to convert a JSON obj using Java JSONObject which is a child class of java.util.HashMap. No organization is delivered. If you want the severe organization of components, use JSONValue.toJSONString ( map ) function with well-ordered map application such as java.util.LinkedHashMap.

import org.json.simple.JSONObject;
class JsonEncodeDemo1 {
   public static void main(String[] args) {
      JSONObject obj1 = new JSONObject();

      Obj1.put("name1", "foo");
      Obj1.put("num1", new Integer(100));
      Obj1.put("balance1", new Double(1000.21));
      Obj1.put("is_vip1", new Boolean(true));

      System.out.print(obj1);
   }
}


On running the above program the subsequent outcome will be produced −
{"balance1": 1000.21, "num1":100, "is_vip1":true, "name1":"foo"}

Subsequent is another sample that displays a JSON obj conversion using Java JSONObject.

import org.json.simple.JSONObject;
class JsonEncodeDemo1 {
   public static void main(String[] args) {
      JSONObject obj1 = new JSONObject();
      Obj1.put("name1","foo");
      Obj1.put("num1",new Integer(100));
      Obj1.put("balance1",new Double(1000.21));
      Obj1.put("is_vip1",new Boolean(true));
      StringWriter out = new StringWriter();
      Obj1.writeJSONString(out);
      String jsonText1 = out.toString();
      System.out.print(jsonText1);
   }
}


On running the above program, the subsequent outcome is generated −
{"balance1": 1000.21, "num1":100, "is_vip1":true, "name1":"foo"}

Another Method:

There is a built in function to transform a JSONObject to a String.

JSONObject json1 = new JSONObject();

Json1.toString()
2,760 points
7 4