S.M_Emamian
S.M_Emamian

Reputation: 17383

java.util.ArrayList cannot be cast to myclass - gson

I want to use Gson library but I get this error :

java.util.ArrayList cannot be cast to UserHelper

The UserHelper is my class helper:

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

value of str variable :

[{"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

solved

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

Upvotes: 0

Views: 1499

Answers (1)

dotvav
dotvav

Reputation: 2848

It seams that str contains an array of UserHelper and you are trying to deserialize it as an ArrayList<UserHelper> which cannot be cast into a UserHelper

If you are certain the list always contain one single item, then you may replace the last line with:

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

Upvotes: 1

Related Questions