Reputation: 1268
I have the below code which will create nested JSON
Object with JSONArray
.
public static void main(String[] args) {
JSONArray array=new JSONArray();
JSONObject jsonObject=new JSONObject();
JSONObject jsonObject1=new JSONObject();
JSONObject jsonObject2=new JSONObject();
jsonObject2.put("testapp", true);
array.put(jsonObject2);
jsonObject1.put("test", array);
jsonObject1.put("test2", false);
jsonObject1.put("app", 1);
jsonObject.put("MAINs", jsonObject1);
System.out.println(jsonObject);
}
Output is:
{"MAINs":{"app":1,"test2":false,"test":[{"testapp":true}]}}
But I wanted to create the map representation of the above JSON object in java like how I have created using JSONObject and JSONArray.
Upvotes: 0
Views: 699
Reputation: 25
You can use toMap method present in org.json library which will convert JSONObject to Map object.
public static void main(String[] args) {
JSONArray array=new JSONArray();
JSONObject jsonObject=new JSONObject();
JSONObject jsonObject1=new JSONObject();
JSONObject jsonObject2=new JSONObject();
jsonObject2.put("testapp", true);
array.put(jsonObject2);
jsonObject1.put("test", array);
jsonObject1.put("test2", false);
jsonObject1.put("app", 1);
jsonObject.put("MAINs", jsonObject1);
System.out.println(jsonObject);
Map<String, Object> map=jsonObject.toMap();
System.out.println(map);
}
Upvotes: 1