jax-rsresteasyjsonb-apiyasson

Force JSON-B to write Numbers as Strings when generating JSON


I'm dealing with large numbers in my Java code and because of the limitations of JavaScript (namely the 32-bit support of Integers), I need to write those numbers as Strings in the JSON returned by my application.

Is there a global configuration or annotation that will allow me to do this? I'd like to avoid writing custom serializers/adapters if possible.

I am using RestEasy with the new JSON-B/Yasson support.


Solution

  • The only way I can think of is using an adapter like this:

    import javax.json.bind.adapter.JsonbAdapter;
    
    public class AdapterIntegerToString implements JsonbAdapter<Integer, String> {
    
        @Override
        public String adaptToJson(Integer obj) throws Exception {
            return String.valueOf(obj);
        }
    
        @Override
        public Integer adaptFromJson(String obj) throws Exception {
            return Integer.parseInt(obj);
        }
    }
    

    And then annotated your property with:

    @JsonbTypeAdapter(AdapterIntegerToString.class)
    private Integer age;
    

    Any other Integer no annotated will be treated as it is by default.