Jackson ignore customized ObjectMapper in API response of Quarkus app

84 views Asked by At

I have the Qurakus app with REST API

@Path("/hello")
public class ExampleResource {

    @GET
    @Consumes(MediaType.APPLICATION_JSON)
    public ObjectNode hello() throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        String str = "{\"var\": 0.000000009}";
        ObjectNode object = (ObjectNode) objectMapper.readTree(str);
        return object;
    }
}

With customized Jackson ObjectMapper as follow:

@Singleton
public class RegisterCustomModuleCustomizer implements ObjectMapperCustomizer {
    public void customize(ObjectMapper mapper) {
        mapper.enable(JsonGenerator.Feature.WRITE_BIGDECIMAL_AS_PLAIN);
    }
}

During response Jackson not invoke customized ObjectMapper, as a result the value returned in scientific notation.

If I use bellow POJO for response, Jackson invoke customized ObjectMapper as needed.

public class Entity {

    public Entity() {
    }

    public Entity(BigDecimal value) {
        this.value = value;
    }

    public BigDecimal value;

    public BigDecimal getValue() {
        return value;
    }

    public void setValue(BigDecimal value) {
        this.value = value;
    }
}

Why Jackson ignore customized ObjectMapper?

Jackson need to invoke customized ObjectMapper.

2

There are 2 answers

3
geoand On

Implementations of ObjectMapperCustomizer are only applied to ObjectMapper classes that are managed by CDI (meaning they don't work on instances created with new at random parts of the code)

0
Serkan On

You need to inject the objectMapper managed by Quarkus, and not use your own one:

@Inject ObjectMapper objectMapper;