繁体   English   中英

用于原始类型的Jackson序列化器

[英]Jackson serializer for primitive types

我正在编写一个自定义序列化程序,以将双精度值转换为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}

有没有办法使这两种情况都遵循相同的行为?

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM