简体   繁体   中英

change field name to lowercase while deserializing POJO to JSON using GSON?

I have a POJO class like this. I am deserializing my JSON to below POJO first..

public class Segment implements Serializable {
  @SerializedName("Segment_ID")
  @Expose
  private String segmentID;
  @SerializedName("Status")
  @Expose
  private String status;
  @SerializedName("DateTime")
  @Expose
  private String dateTime;
  private final static long serialVersionUID = -1607283459113364249L;

  ...
  ...
  ...

  // constructors
  // setters
  // getters
  // toString method
}

Now I am serializing my POJO to a JSON like this using Gson and it works fine:

Gson gson = new GsonBuilder().create();
String json = gson.toJson(user.getSegments());
System.out.println(json);

I get my json printed like this which is good:

[{"Segment_ID":"543211","Status":"1","DateTime":"TueDec2618:47:09UTC2017"},{"Segment_ID":"9998877","Status":"1","DateTime":"TueDec2618:47:09UTC2017"},{"Segment_ID":"121332121","Status":"1","DateTime":"TueDec2618:47:09UTC2017"}]

Now is there any way I can convert "Segment_ID" to all lowercase while deserializing? I mean "Segment_ID" should be "segment_id" and "Status" should be "status". Is this possible to do using gson? So it should print like this instead.

[{"segment_id":"543211","status":"1","datetime":"TueDec2618:47:09UTC2017"},{"segment_id":"9998877","status":"1","datetime":"TueDec2618:47:09UTC2017"},{"segment_id":"121332121","status":"1","datetime":"TueDec2618:47:09UTC2017"}]

if I change the "SerializedName" then while deserializing my JSON to POJO, it doesn't work so not sure if there is any other way.

You need to provide alternative names for deserialisation process and primary ( value property) for serialisation.

class Segment {

    @SerializedName(value = "segment_id", alternate = {"Segment_ID"})
    @Expose
    private String segmentID;

    @SerializedName(value = "status", alternate = {"Status"})
    @Expose
    private String status;

    @SerializedName(value = "datetime", alternate = {"DateTime"})
    @Expose
    private String dateTime;

}

Now, you can deserialise fields: Segment_ID , DateTime , Status and still be able to serialise as desired.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM