簡體   English   中英

使用GSON將POJO序列化為不同名稱的JSON?

[英]Serialize POJO to JSON with different names using 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 = 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<ClientStats> {

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM