Android : Using Retrofit with generic types for JSON Response

on Tuesday, September 2, 2014


Help please T_T been digging for 2 days for a solution to this problem!


I am using Retrofit to make some networking tasks in my app, One of the APIs that I am calling returns a different object sometimes, but i know when and what it will return everytime I call it.


In this case the Message is an object



{
"key": "some key",
"category": "some category",
"channel": "some channel",
"status": "some status",
"message": {
"someValue": "54",
"someOtherValue": "5353"
}
}


and here the Message is a string



{
"key": "some key",
"category": "some category",
"channel": "some channel",
"status": "some status",
"message": "this is a string"
}


so I am trying to achieve a good design of this solution by using generics, I have a generic class like this,


ContentResponse Class



public class ContentResponse<T> {

private List<Content<T>> content = new ArrayList<Content<T>>();

public List<Content<T>> getContent() {
return content;
}

public void setContent(List<Content<T>> content) {
this.content = content;
}

private final Class<T> type;

public ContentResponse(Class<T> type) {
this.type = type;
}

public Class<T> getMyType() {
return this.type;
}
}


Content Class



public class Content<T>
{
private String key;
private String category;
private String channel;
private String status;
private T message;

public String getKey() {
return key;
}

public void setKey(String key) {
this.key = key;
}

public String getCategory() {
return category;
}

public void setCategory(String category) {
this.category = category;
}

public String getChannel() {
return channel;
}

public void setChannel(String channel) {
this.channel = channel;
}

public String getStatus() {
return status;
}

public void setStatus(String status) {
this.status = status;
}
}


ContentInterface Class



public interface ContentInterface<T>
{
@GET("/public/content/{category}")
ContentResponse<T> getContent(@Path(PathParameters.CATEGORY) String category);
}


The issue lies here



public class ContentRequest<T> extends RetrofitSpiceRequest<ContentResponse<T>, ContentInterface<T>>
{
String category;

public ContentRequest(Class<ContentResponse<T>> clazz, Class<ContentInterface<T>> retrofittedInterfaceClass, String category) {
super(clazz, retrofittedInterfaceClass);
this.category = category;
}


@Override
public ContentResponse<T> loadDataFromNetwork() throws Exception {
return getService().getContent(category);
}
}


In this context i know that the object returned is a Map<String, String>



contentRequest = new ContentRequest(new Class<ContentResponse<Map<String, String>>>(),
new Class<ContentInterface<Map<String, String>>>(),
"appstrings");


but i get this !!



'class()' is not public in java.lang.Class



i cant just call ContentResponse<Map<String,String>>.class, so what can I do here ?


0 comments:

Post a Comment