Moshi generic type adapter
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.
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)