簡體   English   中英

使用GSON解析包含對象的數組,該對象包含所需的String

[英]Using GSON to parse an array of objects that contains an object that contains a needed String

首先,這是我要解析的項目。 現在,我正在嘗試從此JSON獲取“名稱”鍵的值。 使用GSON來獲取其他必要的變量我沒有遇到麻煩,但是這個變量比那些要難得多。

 "types": [
        {
            "slot": 2,
            "type": {
                "url": "https://www.pokeapi.co/api/v2/type/4/",
                "name": "poison"
            }
        },
        {
            "slot": 1,
            "type": {
                "url": "https://www.pokeapi.co/api/v2/type/12/",
                "name": "grass"
            }
        }
    ]

這是我的代碼,它使我能夠從Types數組之外的所有所需變量中成功創建treecko對象。

            Gson gson = new Gson();
            PokedexMemberJava treecko = gson.fromJson(jsonPokemon, PokedexMemberJava.class);

我用來嘗試通過JSON創建對象的類。 當我嘗試通過JSON創建對象時,除類型數組(已創建為null)外,所有變量都已成功加載。 這些其他變量是從JSON的不同部分加載的,但是如果需要查看的話,我在這篇文章的底部提供了指向此變量的鏈接。

public class PokedexMemberJava {
    int id;
    String name;
    int height;
    int weight;
    Types[] type;

public PokedexMemberJava(int id, String name, int height, int weight){
    this.id = id;
    this.name = name;
    this.height = height;
    this.weight = weight;
}


}

public class Types {
    public Type typeObject;
    public int slot;

public Types (Type typeObject, int slot){
    this.typeObject = typeObject;
    this.slot = slot;  
}

}

public class Type {
    public String url;
    public String name;

public Type (String url, String name){
    this.url = url;
    this.name = name;
}

}

我花了幾個小時試圖弄清楚這一點,並嘗試使用org.json之類的其他庫來獲取名稱變量,但無濟於事。 我只在上面包含了我嘗試獲取的部分的JSON。 如果出於某種原因您想要查看我嘗試解析的整個JSON對象的外觀,可以在以下位置找到它: https : //pokeapi.co/api/v2/pokemon/252/ 另外,對於本文的任何錯誤或格式錯誤,我深表歉意。 這是我第一次在StackOverflow上發布問題。

您的JSON字段名稱不匹配:

  1. 代替Types[] types; ,您擁有Types[] type; 與json中的types屬性不匹配
  2. 代替Type type; ,您有Type typeObject; 與json中的type屬性不匹配

因此,您有2個選擇:

  1. 重命名java字段以匹配json屬性或
  2. 使用@SerializedName覆蓋屬性名稱:

     public class PokedexMemberJava { @SerializedName("types") Types[] type; ... public class Types { @SerializedName("type") public Type typeObject; 

暫無
暫無

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

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