java.util.ArrayList无法强制转换为myclass - gson

时间:2015-07-29 15:03:48

标签: java android gson

我想使用Gson库,但我收到此错误:

  

java.util.ArrayList无法强制转换为UserHelper

UserHelper是我的班助手:

String user_id="",pass="",show_other_profile="",status="",instagram_link="",
    facebook_link="",google_plus="",telegram_link="",website_link="",birthday="";

str变量的值:

[{"user_id":"27","pass":"c3992a14e2887f551119b8b72b08fe12","show_other_profile":"","status":"","instagram_link":"","facebook_link":"","google_plus":"","telegram_link":"","website_link":"","birthday":""}]
UserHelper h = new UserHelper();
Gson gson = new Gson();
Type listType = new TypeToken<List<UserHelper>>() {}.getType();
h = gson.fromJson(res, listType); // error line

解决

arr_users = gson.fromJson(res, listType);
h = arr_users.get(0);

1 个答案:

答案 0 :(得分:1)

str包含UserHelper数组的接缝,并且您尝试将其反序列化为ArrayList<UserHelper>,无法将其转换为UserHelper

如果您确定该列表始终包含一个项目,那么您可以将最后一行替换为:

h = gson.fromJson(res, listType).get(0);