2

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.

Dhanapal
  • 350
  • 2
  • 7
  • 29

2 Answers2

2

That is very easy, here is an example:

JSONObject min = new JSONObject();
min.put("week", "1");
min.put("year", "2014");

JSONObject max = new JSONObject();
max.put("week", "14");
max.put("year", "2017");

JSONObject json= new JSONObject();
stats.put("min", min);
stats.put("max", max);

System.out.println(json.toString());
meda
  • 45,103
  • 14
  • 92
  • 122
1

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();
}

`

Robert I
  • 1,509
  • 2
  • 11
  • 18