使用GSON将POJO序列化为具有不同名称的JSON? [英] Serialize POJO to JSON with different names using GSON?
本文介绍了使用GSON将POJO序列化为具有不同名称的JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个这样的POJO,我使用GSON序列化为JSON:
public class ClientStats {
private String clientId;
private String clientName;
private String clientDescription;
//这里还有一些字段
// getters and setters
}
以下是我的工作方式:
ClientStats myPojo =新的ClientStats();
Gson gson = new Gson();
gson.toJson(myPojo);
现在我的json会是这样的:
{clientId:100,......}
现在我的问题是:有什么办法可以为我自己的名字
clientId
而不是改变clientId
变量名称? Gson中有任何注释可以在clientId
变量之上使用吗?
我想要这样的东西:
{client_id:100,......}
$ c $您可以使用@SerializedName(client_id)
$ b
解决方案$ b
public class ClientStats {
@SerializedName(client_id)
private String clientId;
private String clientName;
private String clientDescription;
//这里还有一些字段
// getters and setters
}
编辑: 您也可以使用这个以通用方式更改所有字段
Gson gson = new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.create()
I have a POJO like this which I am serializing to JSON using GSON:
public class ClientStats { private String clientId; private String clientName; private String clientDescription; // some more fields here // getters and setters }
Here is how I am doing it:
ClientStats myPojo = new ClientStats(); Gson gson = new Gson(); gson.toJson(myPojo);
Now my json will be like this:
{"clientId":"100", ...... }
Now my question is: Is there any way I can come up with my own name for
clientId
instead of changing theclientId
variable name? Is there any annotation in Gson that I can use here on top ofclientId
variable?I want something like this:
{"client_id":"100", ...... }
解决方案You can use @SerializedName("client_id")
public class ClientStats { @SerializedName("client_id") private String clientId; private String clientName; private String clientDescription; // some more fields here // getters and setters }
Edit:
You can also use this, which change all fields in a generic way
Gson gson = new GsonBuilder() .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .create()
这篇关于使用GSON将POJO序列化为具有不同名称的JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文