francadaval
francadaval

Reputation: 2481

How can I define float/double numbers precision in json from Spring MVC?

How can I set Spring MVC to serialize float or double numbers to json with a limited number of decimals?

Upvotes: 0

Views: 2232

Answers (1)

Master Slave
Master Slave

Reputation: 28559

If you are serializing from bean, the easiset would be to write a custom deserializer, e.g.

public class FloatSerializer extends JsonSerializer<Float> {
    @Override
    public void serialize(Float value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
        if (null == value) {
            jgen.writeNull();
        } else {
            final String serializedValue = null;

            // do your customization here

            jgen.writeNumber(serializedValue);
        }
    }
}

and apply it to the field, e.g.

@JsonSerialize(using = FloatSerializer.class)
public Float getFloatField()

or simply convert the value in the setter of the property if its a one time conversion that works for you

-- Update with respect to the comment

If you want to apply globally than you'll have to use a custom jackson object mapper in your spring mvc and follow the guide for adding modules http://wiki.fasterxml.com/JacksonFeatureModules, the gist is along the following lines

    ObjectMapper mapper = new ObjectMapper();
    // basic module metadata just includes name and version (both for troubleshooting; but name needs to be unique)
    SimpleModule module = new SimpleModule("EnhancedDatesModule", new Version(0, 1, 0, "alpha"));
    // functionality includes ability to register serializers, deserializers, add mix-in annotations etc:
    module.addSerializer(MyBean.class, new MyCustomSerializer());
    module.addDeserializer(MyBean.class, new MyCustomSerializer());
    // and the magic happens here when we register module with mapper:
    mapper.registerModule(module);

Upvotes: 1

Related Questions