使用GSON将POJO反序列化为JSON时将字段名称更改为小写? [英] change field name to lowercase while deserializing POJO to JSON using GSON?
问题描述
我有一个像这样的POJO类.我首先将我的JSON反序列化为POJO以下..
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
}
现在,我正在使用Gson将POJO序列化为JSON,并且工作正常:
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);
我得到这样打印的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"}]
现在,在反序列化时,有什么方法可以将"Segment_ID"转换为所有小写字母?我的意思是"Segment_ID"应为"segment_id",状态"应为状态".使用gson可以做到吗?因此它应该像这样打印.
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"}]
如果我更改了"SerializedName",那么在将JSON反序列化为POJO时,它将无法正常工作,因此不确定是否还有其他方法.
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.
推荐答案
您需要为反序列化过程提供替代名称,并为序列化提供主( value
属性).
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;
}
现在,您可以反序列化字段: Segment_ID
, DateTime
, Status
,并且仍然可以根据需要进行序列化.
Now, you can deserialise fields: Segment_ID
, DateTime
, Status
and still be able to serialise as desired.
这篇关于使用GSON将POJO反序列化为JSON时将字段名称更改为小写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!