0

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.

1
  • you can use the Gson library. You can use its toJson method and it will deserialize any object you send as its input argument. Commented Mar 18, 2020 at 20:38

1 Answer 1

1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.