【问题标题】:Jackson serializer for primitive types原始类型的杰克逊序列化器
【发布时间】:2014-09-20 03:58:34
【问题描述】:

我正在编写一个自定义序列化程序来将双精度值转换为 JSON 对象中的字符串。到目前为止我的代码:

public String toJson(Object obj) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    SimpleModule module = new SimpleModule("DoubleSerializer", new Version(1, 0, 0, ""));

    module.addSerializer(Double.class, new DoubleSerializer());
    mapper.registerModule(module);
    return mapper.writeValueAsString(obj);
}

public class DoubleSerializer extends JsonSerializer<Double> {
    @Override
    public void serialize(Double value, JsonGenerator jgen,
            SerializerProvider provider) throws IOException,
            JsonProcessingException {
        String realString = new BigDecimal(value).toPlainString();
        jgen.writeString(realString);
    }
}

这对 Double(类成员)非常有效,但不适用于 double(原始类型)成员。例如,

    public void test() throws IOException {
        JsonMaker pr = new JsonMaker();
        TestClass cl = new TestClass();

        System.out.println(pr.toJson(cl));

    }

    class TestClass {
        public Double x;
        public double y;
        public TestClass() {
            x = y = 1111142143543543534645145325d;
        }
    }

返回:{"x":"1111142143543543565865975808","y":1.1111421435435436E27}

有没有办法让它在两种情况下都遵循相同的行为?

【问题讨论】:

    标签: java json jackson


    【解决方案1】:

    您可以为基本类型double注册JsonSerializer

    module.addSerializer(double.class, new DoubleSerializer());
    

    【讨论】:

      【解决方案2】:

      您可以使用自定义序列化程序来做到这一点,但有一种更简单的方法。 启用JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS

      mapper.getFactory().enable(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS);
      

      【讨论】:

      • 我认为这是在 v2.3 中添加的。我仅限于 2.2。
      • 我刚刚测试过:你仍然得到科学记数法
      • 实际上这很可能是真的......因为它只是引用数字。不幸的是,虽然有JsonGenerator.Feature.WRITE_BIGDECIMAL_AS_PLAIN,但它只影响BigDecimals,而不影响doubles 或floats。提出问题以为非 BigDecimal 浮点值添加单独的 JsonGenerator.Feature 可能是有意义的。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-11-11
      • 2016-11-11
      • 1970-01-01
      • 2016-07-16
      • 1970-01-01
      • 2018-06-07
      • 2017-11-05
      相关资源
      最近更新 更多