0

Well I had a long post here with lots of data and sample code but I think I've realized the issue and am just looking for confirmation.

Specifically, when using json.getJSONArray(TAG) where json is a JSONObject, this will only work for the JSONObject nearest the array? IE, if there are

{"obj1": {"obj2": {"obj3": {"array":[]}}}} 

then the call must be on object3.getJSONArray? I had thought that I could pull any array out regardless of nesting but that appears not to be the case?

Cheers

3 Answers 3

3

In your case, you should use

  obj1.getJSONObject("obj1").getJSONObject("obj2").getJSONObject("obj3").getJSONArray("array");

To reach that nested array.

Sign up to request clarification or add additional context in comments.

Comments

0

Thats right getJSONArray is searching array object on the level that you actually are.

To get Array you should go : JSONObject mainObject = new JSONObject("{Oject 1: {Object 2: {Object 3: {[ARRAY]}}}}") JSONObject object1 = mainObject.getJSONObject("object 1"); and so on till... JSONArray object1 = object2.getJSONArray("object 3");

Comments

0

You can read about the JSON format here.

Consider these two Java classes

public class Foo {
    private Bar bar;
    private String value;
}

public class Bar {
    private int count;
}

and the objects

Foo foo = new Foo();
foo.value = "some value";
Bar bar = new Bar();
bar.count = 42;
foo.bar = bar;

Could you do

foo.count = 100;

? The answer is no. the field count belongs to the Bar object, not to the Foo object.

Same thing applies to JSON.

{
    "bar": {
        "count": 42
    },
    "value": "some value"
}

The count element is a JSON primitive that belongs to the JSON object named bar.

(The fact that it is a JSON array is irrelevant.)

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.