Nik Myers Nik Myers - 1 year ago 83
Android Question

Gson + Retrofit, how does it work?

I'm using Retrofit to make API requests. The thing is, project hasn't been written by me and currently i'm rewriting API calls, because they were made with manual HttpRequest structure. The issue, is that for some reason to field "photoUrl" if there is none server returns value "false", which is bad, but question was constructed due to this issue. So, that's the field:

private String photoUrl;

I assumed that when Retrofit response will be converted to object, setter will be used to set a value, so temporary i've made a condition to set it as
if "false" is coming to prevent issues in further user interaction with an app, here's setter:

public void setPhoto_url(String photoUrl) {
if(!photoUrl.equals("false")) {
this.photoUrl = photoUrl;

To my surprise, condition is not working at all, and that is what raised my question : Isn't Gson supposed to use setter to set value to private field?

Answer Source

No, GSON uses reflection to set the field value directly.

It does not use getters/setters, and doesn't have the option of using getters/setters either.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download