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. 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;
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.