Tuesday

JSON.simple (a simple Java library) example

In the output section you can find the details of the example.

- Download json-simple-1.1.jar
For maven:

<dependency>
    <groupId>com.googlecode.json-simple</groupId>
    <artifactId>json-simple</artifactId>
    <version>1.1</version>
</dependency>

OUTPUT:

--------------------createJsonText--------------------
{"PARAMETERS":[{"1":"Json 1. value"},{"2":"Json 2. value"},{"3":"Json 3. value"}],"ID":"ABCD"}
--------------------parseJsonText--------------------
ID: ABCD
PARAMETERS in order: 1. value = Json 1. value
PARAMETERS in order: 2. value = Json 2. value
PARAMETERS in order: 3. value = Json 3. value



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


public class Test {
     
      public static void main(String[] args) throws ParseException {
            Test t = new Test();
            String jsonString = t.createJsonText();
            t.parseJsonText(jsonString);
      }

      @SuppressWarnings("unchecked")
      public String createJsonText(){
            System.out.println("--------------------createJsonText--------------------");
           
            JSONArray ja = new JSONArray();
            for(int i = 1 ; i < 4 ; i++) {
                  JSONObject paramsObj = new JSONObject();
                  paramsObj.put(i, "Json " + i + ". value");
                  ja.add(paramsObj);
            }
           
            JSONObject mainObj = new JSONObject();
            mainObj.put("ID", "ABCD");
            mainObj.put("PARAMETERS", ja);
           
            String jsonString = mainObj.toJSONString();
            System.out.println(jsonString);
           
            return jsonString;
      }
     
      public void parseJsonText(String jsonString) throws ParseException {
            System.out.println("--------------------parseJsonText--------------------");
           
            JSONParser parser = new JSONParser();
            JSONObject jo = (JSONObject) parser.parse(jsonString);
           
        System.out.println("ID: " + (String) jo.get("ID"));
          JSONArray msg1 = (JSONArray) jo.get("PARAMETERS");
          if(msg1 != null) {
              for (int i = 0; i < msg1.size(); i++) {
                  JSONObject jsonobject = (JSONObject) msg1.get(i);
                  System.out.println("PARAMETERS in order: " + (i+1) + ". value = "  + (String)jsonobject.get(""+(i+1)));
              }
          }
      }
     
}

No comments:

Post a Comment