简体   繁体   English

如何从Java中的多层数组获取特定值

[英]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. 我正在学习使用Java来解析PHP脚本返回的JSON feed。

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. 我使用gson来完成任务,但正在努力从对象数组访问特定值。 For example, I want to get the value of "name" attribute A in the first object of the array "feature". 例如,我想在数组“功能”的第一个对象中获取“名称” attribute A的值。 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 ? 谁能告诉我如何获取名称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. 我对GSON不太熟悉,但是似乎result.specification.get("result").feature[0]不是您所想的。 Its an ArrayList of Attribute 's. 它是Attribute的ArrayList。 So adding get(0).name instead should do the trick. 因此,添加get(0).name应该可以解决问题。 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 :). 您可以在GSON文档上进行有关如何执行此操作的研究:)。

specification.result.feature.[0] Specification.result.feature。[0]

will give you 会给你

[{"name":"attribute A","value":"50"}] [{“名称”:“属性A”,“值”:“ 50”}]

which is an array with one element. 这是一个只有一个元素的数组。

Now 现在

specification.result.feature.[0].name will give you attribute A specification.result.feature。[0] .name将为您提供属性A

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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