android retrofit post request - exclude field from the body
Visit here for details.
Basically, @Expose will not be regarded by the default Gson instance. In order to utilize it, you'll need to use a custom Gson instance:
GsonBuilder builder = new GsonBuilder();
builder.excludeFieldsWithoutExposeAnnotation();
Gson gson = builder.create();
but if you do this you'll have to add @Expose to every field in all your model classes or they won't be serialised or deserialised by GSON.
I assume you're using Gson. You can use transient
.
private transient int id;
If you require a more complicated solution, take a look at Gson: How to exclude specific fields from Serialization without annotations
This is how to do it with Retrofit
val gson: Gson = GsonBuilder().excludeFieldsWithoutExposeAnnotation().create()
builder = Retrofit.Builder()
.client(okHttpClient)
.baseUrl(URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
And in your model
// These values are read as JSON objects only in server response
@SerializedName("someField")
@Expose(serialize = false, deserialize = true)
var someField: String? = null
For example here, we will not send JSON object to server (deserialize = false) but we will receive it as response (deserialize = true)