Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add string into JsonArray

Tags:

json

android

I am trying to add string values in JsonArray and after that create Json String to send it on server.

I was searching on google but I couldn't find anything helpful. Could anyone tell me how to this? Thanks

 JSONArray list = new JSONArray();
 list.put("Hello");
 list.put("Hey");

After that I want create JSONString

like image 409
fish40 Avatar asked Jun 15 '12 15:06

fish40


People also ask

How can we add a JSONArray to JSONObject in Java?

We can also add a JSONArray to JSONObject. We need to add a few items to an ArrayList first and pass this list to the put() method of JSONArray class and finally add this array to JSONObject using the put() method.

How do I add a list to a JSON object?

How do I add a list to a JSON object? JSONObject obj = new JSONObject(); List sList = new ArrayList (); sList. add(“val1”); sList. add(“val2”); obj.

How do I check if a string is Jsonarject or JSONArray?

JSONArray interventions; if(intervention == null) interventions=jsonObject. optJSONArray("intervention"); This will return you an array if it's a valid JSONArray or else it will give null .

How do I create a JSONArray?

Create a JSON array by instantiating the JSONArray class and add, elements to the created array using the add() method of the JSONArray class.


2 Answers

Simple:

JSONArray list = new JSONArray();
list.put("Hello");
list.put("Hey");

String jsonString = list.toString()

according to docs it should result in "["Hello", "Hey"]"

like image 157
Rafael T Avatar answered Oct 12 '22 09:10

Rafael T


just use

list.toString(2)

this will give you the string in json

like image 22
Simon Meyer Avatar answered Oct 12 '22 08:10

Simon Meyer