简体   繁体   中英

Jackson serializer for primitive types

I am writing a custom serializer to convert double values into strings in JSON objects. My code so far:

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

This works perfectly fine with Double (class members) but does not work for double (primitive type) members. For example,

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

Returns: {"x":"1111142143543543565865975808","y":1.1111421435435436E27}

Is there a way to make it follow same behavior for both cases?

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

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

You can do it with custom serializer, but there is a simpler way to. Enable JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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