How to ignore a JSON element in Android Retrofit

I found an alternative solution if you don't want to use new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create() .

Just including transient in the variable I need to ignore.

So, the POJO class finally:

public class sendingPojo {
    long id;
    String text1;
    transient String text2;//--> I want to ignore that in the JSON

    getId() {
        return id;
    }

    setId(long id) {
        this.id = id;
    }

    getText1() {
        return text1;
    }

    setText1(String text1) {
        this.text1 = text1;
    }

    getText2() {
        return text2;
    }

    setText2(String text2) {
        this.text2 = text2;
    }
}

I hope it helps


Mark the desired fields with the @Expose annotation, such as:

@Expose private String id;

Leave out any fields that you do not want to serialize. Then just create your Gson object this way:

Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();

You can configure Retrofit by adding the GSON object from the GSONBuilder into your ConverterFactory, see my example below:

private static UsuarioService getUsuarioService(String url) {
    return new Retrofit.Builder().client(getClient()).baseUrl(url)
            .addConverterFactory(GsonConverterFactory.create(getGson())).build()
            .create(UsuarioService.class);
}

private static OkHttpClient getClient() {
    return new OkHttpClient.Builder().connectTimeout(5, MINUTES).readTimeout(5, MINUTES)
            .build();
}

private static Gson getGson() {
    return new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
}

To ignore the field elements simply add @Expose(deserialize = false, serialize = false) to your properties or none, and for (de)serialize your fields elements you can add the @Expose() annotations with empty values to your properties.

@Entity(indexes = {
        @Index(value = "id DESC", unique = true)
})
public class Usuario {

    @Id(autoincrement = true)
    @Expose(deserialize = false, serialize = false) 
    private Long pkey; // <- Ignored in JSON
    private Long id; // <- Ignored in JSON, no @Expose annotation
    @Index(unique = true)
    @Expose
    private String guid; // <- Only this field will be shown in JSON.