0

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));
pirho
  • 11,565
  • 12
  • 43
  • 70
Vytsalo
  • 670
  • 3
  • 9
  • 19

1 Answers1

1

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;
    }
});
pirho
  • 11,565
  • 12
  • 43
  • 70
  • Thanks. But then option setDateFormat("dd.MM.yyyy") don't working. How to fix it? – Vytsalo Dec 19 '19 at 04:48
  • @Vytsalo you just need to call the `setDateFormat(...)` with the inner Gson in the adapter, if I got your problem right. Updated answer – pirho Dec 19 '19 at 08:30