I am trying to create this JSON object on android. I am stuck on how to add a string array in the object.
A = {
\"class\" : \"4\" ,
\"name\" : [\"joh
@bhavindesai's, answer is great answer. Here is another way to solve this issue. You can simply do it using Json Simple library. Here is the gradle
compile 'com.googlecode.json-simple:json-simple:1.1'
Here is sample code:
org.json.simple.JSONObject jsonObject=new org.json.simple.JSONObject();
jsonObject.put("Object","String Object");
ArrayList<String> list = new ArrayList<String>();
list.add("john");
list.add("mat");
list.add("jason");
list.add("matthew");
jsonObject.put("List",list);
That's it. :)
As bhavindesai noted,
ArrayList<String> list = new ArrayList<String>();
list.add("john");
list.add("mat");
list.add("jason");
list.add("matthew");
JSONObject school = new JSONObject();
school.put("class","4");
school.put("name", new JSONArray(list));
is a much better and cleaner approach.
To import the right package you should write:
import org.json.simple.JSONArray;
on top of java class.
And if you are using Maven, add
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1</version>
</dependency>
to pom.xml. Then, Download sources & dependencies and Reimport. I answered though I used commenting, since commenting screwed up the code indentation.
You are getting error because of this.
school.put("name", ["john", "mat", "jason", "matthew"] );
^ ^
Do like this.
school.put("name", new JSONArray("[\"john\", \"mat\", \"jason\", \"matthew\"]"));
Little improper approach suggested by Tom. Optimised code would be:
ArrayList<String> list = new ArrayList<String>();
list.add("john");
list.add("mat");
list.add("jason");
list.add("matthew");
JSONObject school = new JSONObject();
school.put("class","4");
school.put("name", new JSONArray(list));
You're getting an error because your last line is invalid Java.
school.put("name", new JSONArray("[\"john\", \"mat\", \"jason\", \"matthew\"]"));