Menu Search Sign up

Java JSON Library

Here is an example of parsing JSON string into a Java object and vice versa:

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public static MyObject fromJason(String jsnStr) {

MyObject item = null;

try {
   JSONParser parser = new JSONParser();
   Object obj=parser.parse(jsnStr);
   if (obj!=null) {
      JSONObject jobj =(JSONObject)obj;
       if (jobj!=null) {
          String id = (String)jobj.get("id");
          String name = (String)jobj.get("name");
          item = new MyObject(id,name);}

   }
}catch (Exception e) {
}

return item;
}

public static String toJason(MyObject item) {
String rtn = null;

if (item!=null) {
   JSONObject obj=new JSONObject();
   obj.put("id", item.getId());
   obj.put("name", item.getName());

   rtn = obj.toJSONString();
}
return rtn;
}

Here is another example of using JSON array:

JSONParser parser = new JSONParser();
Object obj=parser.parse(jsnStr);
if (obj!=null) {
   JSONArray array=(JSONArray)obj;
   if (array!=null && array.size()>0) {
      MyObject[] items = new MyObject[array.size()];
      for (int i=0; i<items.length; i++) {
      try {
         MyObject item = new MyObject();
         JSONObject jobj = (JSONObject)array.get(i);

          if (jobj!=null) {
             String id = (String)jobj.get("id");
             String name = (String)jobj.get("name");
             item = new MyObject(id,name);}

             items[i] = item;

          }

          items[i] = null;

        } catch (Exception e) {//end try

           items[i] = null;

        }

        }//end for

}//end if

Here is where to get the Java JSON package:

https://code.google.com/p/json-simple/downloads/list
https://code.google.com/p/json-simple/