[英]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字段名稱不匹配:
Types[] types;
,您擁有Types[] type;
與json中的types
屬性不匹配 Type type;
,您有Type typeObject;
與json中的type
屬性不匹配 因此,您有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.