3

I have previously JSON response in REST API like below,

Example,

{"id":"1234"}.

I created an POJO class to set it like below.

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Example {

    @SerializedName("id")
    @Expose
    private String id;

    /**
     *
     * @return
     * The id
     */
    public String getId() {
        return id;
    }

    /**
     *
     * @param id
     * The id
     */
    public void setId(String id) {
        this.id = id;
    }
}

And I am parsing with GSON like below

Example response = new Gson().fromJson(jsonResponse, Example .class);

Now, response is changed to

{"Id":"1234"}

And my whole parsing is returning me null due to initial capital letter.

I tried many things to solve it out but I can't get any solution for it. I have only suggestions like

  • you should change name of @SerializedName with initial capital (but I have thousands of objects)

Is there any solution that GSON won't depend upon capitalization or lower case of key?

Chintan Rathod
  • 25,864
  • 13
  • 83
  • 93

1 Answers1

3

I think you can use FieldNamingPolicy in your Gson Builder like this :

Gson gson = new GsonBuilder()
                .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
                .create();

I think in your case you will need to use LOWER_CASE_WITH_UNDERSCORES or LOWER_CASE_WITH_DASHES based which separator you want to use.

From the docs if you set this flag it will convert camel cased form to a lower case field name.

EDIT:
The SerializedName annotation will override any field naming policy so you need to be careful with it -> source

Niko Adrianus Yuwono
  • 11,012
  • 8
  • 42
  • 64