使用GSON将POJO序列化为不同名称的JSON?

我有一个像这样的POJO,我使用GSON序列化为JSON:

public class ClientStats { private String clientId; private String clientName; private String clientDescription; // some more fields here // getters and setters } 

我是这样做的:

 ClientStats myPojo = new ClientStats(); Gson gson = new Gson(); gson.toJson(myPojo); 

现在我的json将是这样的:

 {"clientId":"100", ...... } 

现在我的问题是:我有没有办法为clientId自己的名字,而不是更改clientId变量名? 在Gson中是否有任何注释我可以在clientId变量的顶部使用?

我想要这样的东西:

 {"client_id":"100", ...... } 

你可以使用@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 } 

编辑:

您也可以使用它,它以通用方式更改所有字段

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

更进一步是编写实现GSON序列化 JsonSerializer的序列化

 import com.google.gson.JsonSerializer; public class ClientStatsSerialiser implements JsonSerializer { @Override public JsonElement serialize(final ClientStats stats, final Type typeOfSrc, final JsonSerializationContext context) { final JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("client_id", stats.getClientId()); // ... just the same thing for others attributes. return jsonObject; } } 

在这里,您不需要任何注释,您可以编写多个自定义序列化程序。

使用它的主类示例:

 package foo.bar; import com.google.gson.Gson; import com.google.gson.GsonBuilder; public class Main { public static void main(final String[] args) { // Configure GSON final GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(ClientStats.class, new ClientStatsSerialiser()); gsonBuilder.setPrettyPrinting(); final Gson gson = gsonBuilder.create(); final ClientStats stats = new ClienStats(); stats.setClientId("ABCD-1234"); // Format to JSON final String json = gson.toJson(stats); System.out.println(json); } }