我在使用gson反序列化java中的json時非常困難。使用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和綁定的名稱。
預先感謝您
你想解析JSON? –
使用gson庫。這將是非常容易的 – Krish
是的,我想解析它,而我正在使用gson,但我似乎無法弄清楚:/ –