I want to create a object array in JSONObjet. But not run in java. Please help me.
JSONObject jo[] = new JSONObject[10];
jo[0].put("A","a");
jo[1].put("B","b");
jo[2].put("B","c");
...
I want to create a object array in JSONObjet. But not run in java. Please help me.
JSONObject jo[] = new JSONObject[10];
jo[0].put("A","a");
jo[1].put("B","b");
jo[2].put("B","c");
...
You are probably looking for this -
JSONObject jo[] = new JSONObject[10];
jo[0]=new JSONObject().put("A","a");
jo[1]=new JSONObject().put("B","b");
jo[2]=new JSONObject().put("B","c");
Use JSONArray instead of that like this -
public void getJSONArray() throws JSONException {
JSONArray jo= new JSONArray();
JSONObject obj1= new JSONObject();
obj1.put("A","a");
JSONObject obj2= new JSONObject();
obj2.put("B","b");
JSONObject obj3= new JSONObject();
obj3.put("B","c");
jo.put(obj1);
jo.put(obj2);
jo.put(obj3);
System.out.println(jo.toString());
}
Output -
[{"A":"a"},{"B":"b"},{"B":"c"}]
jo[i] = new JSONObject();JSONObject jo[] = new JSONObject[10];gives you an array of 10 null pointers. It does not yet contain any objects. You have to create each of the 10 objects before you can call any methods on them.