Android Gson JSON Serialization/Deserialization with AutoValue and Gson

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!


Import in your gradle root file

classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'

Import in your gradle app file

apt ''  
apt ''  
provided ''  
provided 'org.glassfish:javax.annotation:10.0-b28'

Create object with autovalue:

@AutoValue public abstract class SignIn {    
    @SerializedName("signin_token") public abstract String signinToken();
    public abstract String username();

    public static TypeAdapter<SignIn> typeAdapter(Gson gson) {
        return new AutoValue_SignIn.GsonTypeAdapter(gson);

    public static SignIn create(String signin, String username) {
        return new AutoValue_SignIn(signin, username);

Create your Gson converter with your GsonBuilder

Gson gson = new GsonBuilder()
                    new AutoValueGsonTypeAdapterFactory())


String myJsonData = "{
    \"signin_token\": \"mySigninToken\",
    \"username\": \"myUsername\" }";
SignIn signInData = gson.fromJson(myJsonData, Signin.class);


Signin myData = SignIn.create("myTokenData", "myUsername");
String myJsonData = gson.toJson(myData);

Using Gson is a great way to simplify Serialization and Deserialization code by using POJO objects. The side effect is that reflection is costly performance wise. That's why using AutoValue-Gson to generate CustomTypeAdapter will avoid this reflection cost while staying very simple to update when an api change is happening.

Got any Android Question?