katharsis-project / katharsis-framework

Katharsis adds powerful layer for RESTful endpoints providing implementenation of JSON:API standard
http://katharsis.io
Apache License 2.0
135 stars 65 forks source link

serialization of float value adds many decimal places #446

Closed charybr closed 7 years ago

charybr commented 7 years ago

Serialization of float value using Katharsis api adds many decimal places. When we use spring controller, issue is not seen.

For example: Actual value of temperature is 2.1, but it is serialized as: {"deviceId":"dev1","time":1501237894000,"temperature":2.0999999046325684}

Expected {"deviceId":"dev1","time":1501237894000,"temperature":2.1}

katharsis-spring version: 2.6.0

yogendra commented 7 years ago

This is not a katharisis issue. Its jackson object mapper and float value serialization/rounding issue. You can fix it by adding your custom serializer as follows:

    @Autowired
    private ObjectMapper objectMapper;

    @PostConstruct
    public void init(){
       objectMapper.registerModule(floatModule());
    }
    @Bean
    public Module floatModule(){
        SimpleModule m = new SimpleModule("FloatModule");
        m.addSerializer(Float.class, floatSerializer());
        m.addSerializer(float.class, floatSerializer());
        return m;
    }
    @Bean
    public JsonSerializer<Float> floatSerializer(){
        return new JsonSerializer<Float>() {
            @Override
            public void serialize(Float value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException {
                BigDecimal d = BigDecimal.valueOf(value).setScale(2, BigDecimal.ROUND_HALF_EVEN);
                gen.writeNumber(d);
            }
        };
    }
charybr commented 7 years ago

Thanks Yogendra, for responding!

In the same maven project, using spring controller (that also uses jackson library) issue is not seen. Does Katharsis uses different version of jackson?

yogendra commented 7 years ago

Unlikely. Most likely its using a different ObjectMapper/Module setup.

charybr commented 7 years ago

Thanks Yogendra!