Reputation: 595
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
Upvotes: 0
Views: 106
Reputation: 7586
In your case, you should use
obj1.getJSONObject("obj1").getJSONObject("obj2").getJSONObject("obj3").getJSONArray("array");
To reach that nested array.
Upvotes: 3
Reputation: 280177
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.)
Upvotes: 0
Reputation: 2903
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");
Upvotes: 0