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?

2

3 Answers 3

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

Comments

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.

2 Comments

Why are you passing a List into constructor of JSONArray? It should just accept a String.
I was not able to solve my problem by this so I used JSONArray json = new JSONArray(Arrays.toString(array));
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);

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.