0

When the JSON string {"a": 1} is deserialized, the number 100 should be added to the value 1. In jsonb this is achieved via the setter method, but Gson ignores the setter method. How can Gson be made to use the setter method? Or if this is not possible, what is the recommended alternative for a setter in Gson - in 2022?

@RestController
public class NumberController {
    @RequestMapping("/number")
    public Number number() {
        String jsonString = "{\"a\":1}";

        // Gson.
        GsonBuilder builder = new GsonBuilder();
        Gson gson = builder.create();
        Number numberWithGson = gson.fromJson(jsonString, Number.class);
        System.out.println(numberWithGson); // Number(a=1)

        // Jsonb.
        Jsonb jsonb = JsonbBuilder.create();
        Number numberWithJsonB = jsonb.fromJson(jsonString, Number.class);
        System.out.println(numberWithJsonB); // Number(a=101)

        return numberWithGson; // Returns {"a": 1}, but should return {"a": 101}
    }
}
public class Number {
    private int a;

    public void setA(int a) {
        this.a = a + 100;
    }
}
Anne Maier
  • 299
  • 1
  • 8

1 Answers1

0

I believe you need to mark the property private int a with annotation from GSON library like @Expose or @SerializedName in order for the GSON mechanism to deserialize the JSON string properly. Try to refer to this link for more info and example.

Joey
  • 695
  • 6
  • 19