簡體   English   中英

如何從Java中的多層數組獲取特定值

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

我正在學習使用Java來解析PHP腳本返回的JSON feed。

供稿示例:

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

我使用gson來完成任務,但正在努力從對象數組訪問特定值。 例如,我想在數組“功能”的第一個對象中獲取“名稱” attribute A的值。 但是,我收到一個“名稱無法解析或不是字段”錯誤。

    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
    }

這是我上的整個課程:

 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;

    }

}

誰能告訴我如何獲取名稱attribute A 謝謝。

控制成員訪問權限的文檔可能會很有用。 如果您不了解此問題,則該問題並不明顯。

編輯:

我將保留原始答案,但在這種情況下,這不是您的問題。 我對GSON不太熟悉,但是似乎result.specification.get("result").feature[0]不是您所想的。 它是Attribute的ArrayList。 因此,添加get(0).name應該可以解決問題。 話雖如此,如果那不是您要嘗試的工作,那么您可能必須重新評估您的結構。 您可以在GSON文檔上進行有關如何執行此操作的研究:)。

Specification.result.feature。[0]

會給你

[{“名稱”:“屬性A”,“值”:“ 50”}]

這是一個只有一個元素的數組。

現在

specification.result.feature。[0] .name將為您提供屬性A

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM