简体   繁体   中英

How to create JSONArray using map in java

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM