我有一个这样的POJO,我使用GSON序列化为JSON:
public class ClientStats {
private String clientId;
private String clientName;
private String clientDescription;
// some more fields here
// getters and setters
}
Run Code Online (Sandbox Code Playgroud)
我是这样做的:
ClientStats myPojo = new ClientStats();
Gson gson = new Gson();
gson.toJson(myPojo);
Run Code Online (Sandbox Code Playgroud)
现在我的json将是这样的:
{"clientId":"100", ...... }
Run Code Online (Sandbox Code Playgroud)
现在我的问题是:有什么方法可以提出我自己的名字,clientId而不是更改clientId变量名称?在Gson中是否有任何注释我可以在clientId变量顶部使用?
我想要这样的东西:
{"client_id":"100", ...... }
Run Code Online (Sandbox Code Playgroud)
Der*_*ung 12
你可以使用@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
}
Run Code Online (Sandbox Code Playgroud)
编辑:
您也可以使用它,它以通用方式更改所有字段
Gson gson = new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.create()
Run Code Online (Sandbox Code Playgroud)