![](/img/trans.png)
[英]GSON serialisation - how to exclude some fields from serialisation, but not deserialisation
[英]Gson how to exclude some fields in JsonSerializer
我只需要更改一個字段,另一個字段我想擁有 dafault 值,但是使用此代碼我在輸出中只有一個字段 - 我在 JsonSerializer 中編寫的那個,但我需要擁有所有字段並且只有一個用於更改。 有沒有財產的方法?
GsonBuilder gson = new GsonBuilder().serializeNulls();
gson.registerTypeAdapter(TripCardView.class, new JsonSerializer<TripCardView>() {
@Override
public JsonElement serialize(TripCardView src, Type typeOfSrc, JsonSerializationContext context) {
JsonObject jObj = new JsonObject();
jObj.add("numberShortYear", new JsonPrimitive(src.getNumberShortYear()));
return jObj;
}
});
jsonResponse.add("aaData", gson.setDateFormat("dd.MM.yyyy").create().toJsonTree(result));
只是一些小改動,見下面代碼中的注釋:
gson.registerTypeAdapter(TripCardView.class, new JsonSerializer<TripCardView>() {
// You need to create a new Gson in your serializer because calling original contex
// would call this serializer again and cause stack overflow because of recursion
private Gson gson = new GsonBuilder().setDateFormat("dd.MM.yyyy").create();
@Override
public JsonElement serialize(TripCardView src, Type typeOfSrc,
JsonSerializationContext context) {
// You need to serialize the original object to have its fields populated 'default'
JsonElement result = gson.toJsonTree(src);
// After that it is just to add the extra field with value from method call
result.getAsJsonObject().add("numberShortYear",
new JsonPrimitive(src.getNumberShortYear()));
return result;
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.