Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a JSONArray

Tags:

java

json

android

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?

like image 314
meh Avatar asked Nov 07 '12 11:11

meh


People also ask

How do you initiate JSONArray?

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.

What is JSONArray in Java?

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.

What is the correct way to write a JSON array?

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.

What is the use of JSONArray?

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.


1 Answers

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.

Creating time:

For example:

JSONArray myArray = new JSONArray();
JSONObject j = new JSONObject();
j.put("key",value);
j.put("array",myArray);

Retrieving time:

you can fetch the value of String or JSONObject or any by their key name. For example:

JSONArray myArray = objJson.getJSONArray("array");
like image 170
Paresh Mayani Avatar answered Sep 19 '22 13:09

Paresh Mayani