Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用GSON将POJO序列化为具有不同名称的JSON?_Java_Json_Gson - Fatal编程技术网

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

Java 使用GSON将POJO序列化为具有不同名称的JSON?,java,json,gson,Java,Json,Gson,我有一个类似这样的POJO,我正在使用GSON将其序列化为JSON: public class ClientStats { private String clientId; private String clientName; private String clientDescription; // some more fields here // getters and setters } 我是这样做的: ClientStats myPojo

我有一个类似这样的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", ...... }
{"client_id":"100", ...... }
现在我的问题是:我有没有办法为
clientId
想出自己的名字,而不是更改
clientId
变量名?Gson中是否有任何注释可以在
clientId
变量之上使用

我想要这样的东西:

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

您可以使用@SerializedName(“客户端id”)

编辑:

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

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

进一步的步骤是编写实现GSON序列化程序JsonSerializer的序列化程序:

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);
  }
}