9

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?

Valerio Bozz
  • 1,176
  • 16
  • 32
meh
  • 22,090
  • 8
  • 48
  • 58

3 Answers3

14

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");
Paresh Mayani
  • 127,700
  • 71
  • 241
  • 295
7

You can do it like:

String[] data = {"stringone", "stringtwo"};
JSONArray json = new JSONArray(Arrays.toString(data));

Or, create a JSONArray object and use the put method(s) to add any Strings you want. To output the result, just use the toString() method.

Nermeen
  • 15,883
  • 5
  • 59
  • 72
6

Why dont you use Gson library its very easy to convert any object into json array, json object

Download Gson library then use like

Gson gson=new Gson();

String json=gson.toJson(object);

if Object is of List object it will create json array

Gson gson = new Gson();

reverse parsing for array -- 
        listObject = gson.fromJson(json,
                new TypeToken<List<ClassName>>() {
                }.getType());

for single object

object = gson.fromJson(json, ClassName.class);
Mohd Mufiz
  • 2,236
  • 17
  • 28