Moshi generic type adapter

8.9k views Asked by At

Suppose have the following parameterised data class representing a server response:

public class SocketResponse<T> {
    private String responseMessage;
    private int responseCode;
    private T entity;
}

I know at runtime what type T will be. does moshi support generic type adapter the same way Gson does? With Gson id do the following to parse this.

Type typeA = new TypeToken<SocketResponse<MyResponseA>>(){}.getType();
SocketResponse<MyResponseA> responseA = getResponse("json", typeA);

Type typeB = new TypeToken<SocketResponse<MyResponseB>>(){}.getType();
SocketResponse<MyResponseB> responseB = getResponse("json", typeB);


private String getResponse(Type t){
    return gson.fromJson(response, type);
}
3

There are 3 answers

1
Esperanz0 On

I'm mostly using GSON but maybe something like that?

Type type = Types.newParameterizedType(SocketResponse.class, Object.class);
JsonAdapter<SocketResponse<?>> jsonAdapter = moshi.adapter(type);
0
Eric Cochran On

Moshi uses the factory methods on Types to get Java Types in contrast to Gson's TypeToken API.

Type typeA = Types.newParameterizedType(SocketResponse.class, MyResponseA.class);
JsonAdapter<SocketResponse<MyResponseA>> adapter = moshi.adapter(typeA);

Then, use the JsonAdapter to deserialize and serialize your type, just like Gson's TypeAdapter.

0
ryanhex53 On

Just for a more complex situation, if T equals a generic type like this List<MyResponseA>. you can do this for example (in kotlin):

val t = Types.newParameterizedType(
    SocketResponse::class.java, Types.newParameterizedType(
        List::class.java,
        MyResponseA::class.java
    )
)
val adapter = moshi.adapter<SocketResponse<List<MyResponseA>>>(t)