Search code examples
javajsonservletsmulti-level

How to create multi level JSON data using JSONObject in servlet


I need to create JSON data like below,

{
  "min": {
    "week": "1",
    "year": "2014"
  },
  "max": {
    "week": "14",
    "year": "2017"
  }
}

But JSONObject accepts only "id","value" format. So how can I create JSON data using JSONObject like mentioned above.


Solution

  • Tested this in eclipse already for you. `

    String s = "{ \"min\": { \"week\": \"1\", \"year\": \"2014\" }, \"max\": { \"week\": \"14\", \"year\": \"2017\" } }";
    JSONParser parser = new JSONParser();
    try {
        JSONObject json = (JSONObject) parser.parse(s);
        System.out.println(json.get("min"));
        // this will output
        //{"week":"1","year":"2014"}
    } catch (Exception e){
        e.printStackTrace();
    }
    

    `