Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moshi generic type adapter

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);
}
like image 292
sirFunkenstine Avatar asked Sep 13 '17 09:09

sirFunkenstine


People also ask

What types does Moshi support?

Moshi comes with built-in support for standard Java types, converting to and from JSON exactly as expected. This covers: All primitives – int, float, char, etc.

What is Moshi in Java?

In this tutorial, we'll take a look at Moshi, a modern JSON library for Java that will give us powerful JSON serialization and deserialization in our code with little effort. Moshi has a smaller API than other libraries like Jackson or Gson without compromising on functionality.

What is the Squareup Moshi dependency?

The com.squareup.moshi:moshi dependency is the main library, and the com.squareup.moshi:moshi-adapters dependency is some standard type adapters – which we'll explore in more detail later. 3. Working with Moshi and JSON

How do I change the name of a field in Moshi?

We can use the @Json annotation to give a new name to any field in any bean that we control: Once we've done this, Moshi immediately understands that this field has a different name in the JSON: 6.2. Transient Fields In certain cases, we may have fields that should not be included in the JSON.


1 Answers

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.

like image 127
Eric Cochran Avatar answered Sep 28 '22 13:09

Eric Cochran