0

I am hoping to get some direction on how to resolve this issue. I am working with a Third Party API get JSON data. It has a structure similar to:

{items: [
    {attribute : Value},
    {attribute : Value}]
 count : value,
 etc
}

The items array can hold different data, so I have a class:

public Items<T> {
    private List<T> items;
    // Others API Variables

    public List<T> getItems(){
        return items;
    }

    public void setItems(List<T> items){
       this.items = items;
    }
    // Other Getters/Setters
}

What I am trying to do in the calling class is:

public CallingClass {

    public void Method(){
    //Code to get reader object
    Items<User> userItems = Gson().fromJson(ReaderObject, Items.class);
    //Other processing code
    }
}

And I get the error:

java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to User.class

I was reading through this post and I think the solution is similar to what I need but I don't know who to do it. My though was to have a single Items class that could be passed the different Types which are returned.

Thoughts, assistance, anything would be helpful.

EDIT:

OK So I feel like an idiot now, but some sleep helped. The solution was in the link I posted, I was just didn't need a list. My coded solution is as follows:

public CallingClass {

    public void Method(){
    //Code to get reader object
    Items<User> userItems = Gson().fromJson(ReaderObject, new TypeToken<Items<User>>(){}.getType());
    //Other processing code
    }
}
Community
  • 1
  • 1
Shane Andrie
  • 129
  • 1
  • 8
  • 1
    You literally linked to the duplicate of your post. You just need to copy-paste the answer and replace with your own class names. Didn't `new TypeToken>() { }.getType();` work? – Joffrey Mar 29 '17 at 22:44
  • Yup, a simple class of `Items.class` isn't enough. You need to construct the full `Type` via `new TypeToken>() { }.getType();` – kaqqao Mar 30 '17 at 13:01
  • Possible duplicate of [Google Gson - deserialize list object? (generic type)](http://stackoverflow.com/questions/5554217/google-gson-deserialize-listclass-object-generic-type) – kaqqao Mar 30 '17 at 13:01

1 Answers1

0

OK So I feel like an idiot now, but some sleep helped. The solution was in the link I posted, I was just didn't need a list. My coded solution is as follows:

public CallingClass {

    public void Method(){
    //Code to get reader object
    Items<User> userItems = Gson().fromJson(ReaderObject, new TypeToken<Items<User>>(){}.getType());
    //Other processing code
    }
}
NealWalters
  • 17,197
  • 42
  • 141
  • 251
Shane Andrie
  • 129
  • 1
  • 8