我正在使用Raturofit 2.0和Gson将JSON转换为POJO。我关注JSON对象
{
"type": "champion",
"format": "standAloneComplex",
"version": "9.6.1",
"data": {
"Aatrox": {...},
"Ahri": {...},
...
} }
我的问题是,每个条目是一个新类(它是同一类,但命名为不同)
我可以分开访问每个类
public class Champions {
@SerializedName("type")
@Expose
public String type;
@SerializedName("format")
@Expose
public String format;
@SerializedName("version")
@Expose
public String version;
@SerializedName("data")
@Expose
public Data data;
这有效
public class Data {
@SerializedName("Aatrox")
@Expose
public Champion aatrox;
@SerializedName("Ahri")
@Expose
public Champion ahri;}
但是
public class Data {
publc List<Champion> champions = new ArrayList<>();
不
我如何获取列表中的所有条目?
我试图将List<Champion>
放在Data
中,但我不知道该放入@SerializedName
中。
有什么建议如何从数据中检索List<Champion>
?
我从http://ddragon.leagueoflegends.com/cdn/9.6.1/data/en_us/champion.json.json.json
设置您的data
变量数据类型Map<String, Champion>
,而不是将其设置为object
或List
,然后将下面的Getter方法添加到模型中以检索List<Champion>
public List<Champion> getChampions(){
if(data != null){
return new ArrayList<Value>(data.values());
}
return null; // you can set return new ArrayList<>(); to avoid null exception
}
我在项目中使用了一个代码。也许会起作用。自己安排。
Map<String, Champion> championList;
List<String> keyset = new ArrayList<>(championList.keySet());
List<String> values = new ArrayList<>(championList.values());
for (int i = 0; i < values.size(); i++) {
NewItem item = new NewItem(values.get(i), keyset.get(i));}