Why JSONObject converts stringified array to JSONArray on put operation? How to stop this?



  • When I tried to put stringified array in JSONObject, it became a JSONArray. But I want to keep the stringified array. Any help will be appreciated.

eg:

JSONObject jsonObj = new JSONOject();

jsonObj.put("stringified_array", "[1,2]");

So, when I debugged it, the jsonObj properties were

key : "stringified_array", value : [1,2] (JSONArray)

Edit: Here is the link for sample code: https://onlinegdb.com/UbV6VXvpJ. Code won’t compile due to missing packages in online ide, just for better understanding of scenario I have added the link.

Answer

Here is why, if you look at the declaraction of constructor of JSONObject, you will find what you are looking for. One of the constructor of JSONObject class looks like following:

public org.json.JSONObject put(java.lang.String key, java.util.Map<?,?> value) throws org.json.JSONException { /* compiled code */ }

If you know how to do reverse engineering, you should be able to find more about the actual implementation :)!

Hopefully, this will help you out!



Source: stackoverflow