gpt4 book ai didi

java - 如何从更深一层将对象绑定(bind)到数组 1 之外

转载 作者:行者123 更新时间:2023-12-01 18:11:13 25 4
gpt4 key购买 nike

我想建立一个扑克 dex,在那里我可以看到所有神奇宝贝的所有信息。现在我使用pokedex api https://pokeapi.co/api/v2/pokemon/3我想要一份他与神奇宝贝的所有统计数据的列表。我得到的json被分成2个对象

stats": [

{
"base_stat": 80,
"effort": 0,
"stat": {
"name": "speed",
"url": "https://pokeapi.co/api/v2/stat/6/"
}
},
{
"base_stat": 100,
"effort": 1,
"stat": {
"name": "special-defense",
"url": "https://pokeapi.co/api/v2/stat/5/"
}
},
......
]

这样它就不会自动链接到 1 个对象,例如:

stats": [

{
"base_stat": 80,
"effort": 0,
"name": "speed",
"url": "https://pokeapi.co/api/v2/stat/6/"
},
{
"base_stat": 100,
"effort": 1,
"name": "special-defense",
"url": "https://pokeapi.co/api/v2/stat/5/"
},
......
]

我该怎么做?我尝试了这个,这有效,但它似乎不是解决方案。

public class Type {
private PType type;
private int base_stat;
private int effort;

public Type(PType type, int base_stat, int effort){this.type = type; this.base_stat = base_stat; this.effort = effort;}

public class PType{
private String name;
public String getName() {return this.name;}
}

//getters&setters
....
}

最佳答案

使用TypeAdapter (javadocs)。

    public static void main(String[] args) {
String inputJson = "{\"base_stat\": 80,...}";
Gson gson = new GsonBuilder().registerTypeAdapter(Stats.class, new StatsTypeAdapter()).create();
Stats stats = gson.fromJson(inputJson, Stats.class);
}

class Stats {
private int baseStat;
private int effort;
private String name;
private String url;

// getters/setters
}

public class StatsTypeAdapter extends TypeAdapter<Stats> {

private static final JsonParser PARSER = new JsonParser();
private static final Gson GSON = new GsonBuilder().create();

@Override
public void write(JsonWriter out, Stats value) throws IOException {
if (value == null) {
out.nullValue();
} else {
JsonObject json = new JsonObject();
// convert back to JSON...
out.jsonValue(GSON.toJson(json));
}
}

@Override
public Stats read(JsonReader in) throws IOException {
JsonObject json = PARSER.parse(in).getAsJsonObject();
Stats stat = new Stats();
stat.setBaseStat(json.get("base_effort").getAsInt());
stat.setEffort(json.get("effort").getAsInt());
JsonObject statJson = json.getAsJsonObject("stat");
stat.setName(statJson.get("name").getAsString());
stat.setUrl(statJson.get("url").getAsString());
}
}

关于java - 如何从更深一层将对象绑定(bind)到数组 1 之外,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60466432/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com