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);
}
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.
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.
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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With