19

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);
}
sirFunkenstine
  • 8,135
  • 6
  • 40
  • 57

3 Answers3

21

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.

Eric Cochran
  • 8,414
  • 5
  • 50
  • 91
2

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)

ryanhex53
  • 577
  • 4
  • 15
0

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

Type type = Types.newParameterizedType(SocketResponse.class, Object.class);
JsonAdapter<SocketResponse<?>> jsonAdapter = moshi.adapter(type);
Esperanz0
  • 1,524
  • 13
  • 35