JSON.simple - Primitive, Object, Array


Advertisements

Using JSONArray object, we can create a JSON which comprises of primitives, object and array.

Following example illustrates the above concept.

Example

import java.io.IOException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

class JsonDemo {
   public static void main(String[] args) throws IOException {
      JSONArray list1 = new JSONArray();
      list1.add("foo");
      list1.add(new Integer(100));

      JSONArray list2 = new JSONArray();       
      list2.add(new Double(1000.21));
      list2.add(new Boolean(true));
      list2.add(null);

      JSONObject obj = new JSONObject();

      obj.put("name", "foo");
      obj.put("num", new Integer(100));
      obj.put("balance", new Double(1000.21));
      obj.put("is_vip", new Boolean(true));
     
      obj.put("list1", list1); 
      obj.put("list2", list2);
      System.out.println(obj);       
   }
}

Output

{"list1":["foo",100],"balance":1000.21,"is_vip":true,"num":100,"list2":[1000.21,true,null],"name":"foo"}
Advertisements