I am writing and android add and using retrofit2 to send data to the server.
I am trying to exclude one field from the the object that is being serialized and sent to the server.
The object is named "Cheer" and I try to exclude the field id from it when being sent to the server. iv'e tried using @Expose(false, false) and explained here and tried to make the field private, but it is still sent to the server. See the api, object and call below. Please note, it workes, the object is added to the server, the only issue is that, id is still sent in the JSON and I need to exclude it from it.
Thanks!!!
public class Cheer {
@Expose(deserialize = false, serialize = false)
private int id;
}
public interface CheersAPI {
String BASE_URL = "url:port";
@POST("/cheers")
Call<Cheer> AddCheer(@Body Cheer cheer);
}
cheersAPI.AddCheer(cheerToAdd).enqueue(new Callback<Cheer>(){
@Override
public void onResponse(Call<Cheer> call, Response<Cheer> response) {
Log.d("in the on response", "done creating a cheer");
}
@Override
public void onFailure(Call<Cheer> call, Throwable t) {
Log.d("failed", "failed to add a cheer here!");
}
});
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.
Send Objects as Request Body Retrofit offers the ability to pass objects within the request body. Objects can be specified for use as HTTP request body by using the @Body annotation. The functionality of Retrofit's @Body annotation hasn't changed in version 2.
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)
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.
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