[英]Gson how to exclude some fields in JsonSerializer
I need only one field to change, another fields i want to have dafault value, but using this code i have only one field in the output - the one i write in JsonSerializer, but i need to have all field and only one for change.我只需要更改一个字段,另一个字段我想拥有 dafault 值,但是使用此代码我在输出中只有一个字段 - 我在 JsonSerializer 中编写的那个,但我需要拥有所有字段并且只有一个用于更改。 There is a method of property for this?有没有财产的方法?
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));
Just few little changes, see comments in the code below:只是一些小改动,见下面代码中的注释:
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.