Jackson序列化器用于原始类型

时间:2014-09-20 03:58:35

标签: java json jackson

我正在编写一个自定义序列化程序,将双值转换为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(类成员)完全正常,但对双(原始类型)成员不起作用。例如,

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

返回:{&#34; x&#34;:&#34; 1111142143543543565865975808&#34;,&#34; y&#34;:1.1111421435435436E27}

对于这两种情况,有没有办法让它遵循相同的行为?

2 个答案:

答案 0 :(得分:12)

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

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

答案 1 :(得分:-1)

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

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