如何在 Spring MVC 的 json 中定义 float/double 数字精度?

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

如何设置 Spring MVC 以将浮点数或双精度数序列化为 json,小数位数有限?

如果您从 bean 序列化,easiset 将是编写自定义反序列化器,例如

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);
        }
    }
}

并将其应用于该字段,例如

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

或者只需转换 属性 的 setter 中的值(如果一次性转换适合您的话)

-- 更新评论

如果您想全局应用,则必须在 spring mvc 中使用自定义 jackson 对象映射器并按照添加模块 http://wiki.fasterxml.com/JacksonFeatureModules 的指南进行操作,要点如下行

    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);