简体   繁体   中英

How to get a specific value from a multi-layer array in Java

I'm learnign to use Java to parse JSON feeds returned from PHP scripts.

Example feed:

{"specification":{"result":{"feature":[{"name":"attribute A","value":"50"}]}}}

I use gson for the task but I am struggling to access a specific value from the array of objects. For example, I want to get the value of "name" attribute A in the first object of the array "feature". However I'm receiving a "name cannot be resolved or not a field" error.

    public static String show() throws Exception {

        String json = Json.fetch("http://somthing.json");

        Gson gson = new Gson(); 

        Model result = gson.fromJson(json, Model.class);

        return result.specification.get("result").feature[0].name; //Error : name cannot be resolved or not a field
    }

Here is the entire class I came up:

 public class Item {

    static class Model{
        HashMap <String,Item.Data> specification;
    }

    static class Data{
        ArrayList <Item.Attribute> feature[];
    }

    static class Attribute{
        String value;
        String name;
    }

    public static String show() throws Exception {

        String json = Json.fetch("http://somthing.json");

        Gson gson = new Gson(); 

        Model result = gson.fromJson(json, Model.class);

        return result.specification.get("result").feature[0].name;

    }

}

Can anyone show me how to get the name attribute A ? Thank you.

The doc on controlling access to members may be useful. The issue isn't obvious if you don't understand this.

Edit:

I am leaving my original answer, but in this case it is not your problem. I was not too familiar with GSON, but it seems result.specification.get("result").feature[0] is not what you think. Its an ArrayList of Attribute 's. So adding get(0).name instead should do the trick. That being said, you may have to reevaluate your structure if that is not what you were trying to do. You can do the research on how to do this on the GSON docs :).

specification.result.feature.[0]

will give you

[{"name":"attribute A","value":"50"}]

which is an array with one element.

Now

specification.result.feature.[0].name will give you attribute A

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