How to serialize BigDecimal to map value with jackson?

Viewed 3154

Having troubles with serializing BigDecimal object to Map using jackson version 2.7.3 (I can't change this version on my project). It's always serialized as Double. Code I use for serialization:

public static Map<String, Object> serializeToMap(Object pojo) {
    return new ObjectMapper().convertValue(pojo, new HashMap<String, Object>() {}.getClass());
}

Tried to add:

@JsonSerialize(typing = JsonSerialize.Typing.STATIC, as = BigDecimal.class)

and used serializer:

public void serialize(BigDecimal value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
    jgen.writeObject(value.toString());
}

Is it possible to serialize it as BigDecimal?

1 Answers

I solved this by replacing serialization with:

return new ObjectMapper()
    .enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS)
    .convertValue(pojo, new HashMap<String, Object>() {}.getClass());
Related