简体   繁体   中英

Getting an array from a JSON Object

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

In your case, you should use

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

To reach that nested array.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM