How can I create a JSONArray, since creating a JSONObject is quite simple:
JSONObject j = new JSONObject();
j.put("key",value);
Right now I can put another string in the JSONObject, or a string representation of a JSONObject.
But how can I create a JSONArray and insert it to the JSONObject?
jsonObject. put("key", "value"); Create a JSON array by instantiating the JSONArray class and add, elements to the created array using the add() method of the JSONArray class.
A JSONArray is an ordered sequence of values. Its external text form is a string wrapped in square brackets with commas separating the values. The internal form is an object having get and opt methods for accessing the values by index, and put methods for adding or replacing values.
A JSON array contains zero, one, or more ordered elements, separated by a comma. The JSON array is surrounded by square brackets [ ] . A JSON array is zero terminated, the first index of the array is zero (0). Therefore, the last index of the array is length - 1.
JsonArray represents an immutable JSON array (an ordered sequence of zero or more values). It also provides an unmodifiable list view of the values in the array. A JsonArray object can be created by reading JSON data from an input source or it can be built from scratch using an array builder object.
But how can I create a JSONArray and insert it to the JSONObject?
You can create JSONArray same like you have tried to create JSONObject.
For example:
JSONArray myArray = new JSONArray();
JSONObject j = new JSONObject();
j.put("key",value);
j.put("array",myArray);
you can fetch the value of String or JSONObject or any by their key name. For example:
JSONArray myArray = objJson.getJSONArray("array");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With