我在使用 gson 在 java 中反序列化 json 时遇到了非常困难的时间。
我有以下 json:
{"races":[
{"id":1,"mask":1,"side":"alliance","name":"Human"},
{"id":2,"mask":2,"side":"horde","name":"Orc"},
{"id":3,"mask":4,"side":"alliance","name":"Dwarf"}]}
我现在的java代码是:
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Gson gson = new Gson();
Type type = new TypeToken<List<WoWDetails>>(){}.getType();
List<WoWRaces> races = gson.fromJson(response, type);
for (WoWRaces race : races){
if(raceID.equals(race.id)) {
raceName = race.name;
}
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
errorMSG = (TextView) findViewById(R.id. textView5);
errorMSG.setText("That didn't work! URL: \n"+error);
errorMSG.setVisibility(View.VISIBLE);
}
});
在 WoWRaces.java 中有以下代码:
WoWRaces.java
public class WoWRaces {
public Integer id;
public String name;
}
它给了我以下错误:
Expected BEGIN_ARRAY but was BEGIN_OBJECT
我搜索并访问了多个问题,但我似乎无法弄清楚这一点。我需要的数据是 id 和绑定(bind)到它的名称。
提前谢谢
最佳答案
如果您正在使用 gson 库,请尝试这个
Gson gson = new Gson();
MainResponse mainResponse = gson.fromJson(response, MainResponse.class);
List<Race> races = mainResponse.getRaces();
for (Race race : races) {
Log.e("TEST","Race id : " + race.getId());
Log.e("TEST","Race Name : " + race.getName());
}
MainResponse.java
public class MainResponse {
@SerializedName("races")
@Expose
private List<Race> races = null;
public List<Race> getRaces() {
return races;
}
public void setRaces(List<Race> races) {
this.races = races;
}
}
Race.java
public class Race {
@SerializedName("id")
@Expose
private int id;
@SerializedName("mask")
@Expose
private int mask;
@SerializedName("side")
@Expose
private String side;
@SerializedName("name")
@Expose
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getMask() {
return mask;
}
public void setMask(int mask) {
this.mask = mask;
}
public String getSide() {
return side;
}
public void setSide(String side) {
this.side = side;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
关于java - java中使用gson反序列化json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43516638/