1

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");
    ...

2
  • Please, initialize every element with jo[i] = new JSONObject(); Commented Jul 22, 2014 at 8:59
  • Eplanation of the previous comment: 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. Commented Jul 22, 2014 at 9:01

1 Answer 1

3

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

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.