I am writing a special serializer to convert double values ββto strings in JSON objects. My code is:
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 fine with Double (class members), but does not work for elements with a double (primitive type). For instance,
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;
}
}
Refunds: {"x": "1111142143543543565865975808", "y": 1.1111421435435436E27}
Is there a way to get him to follow the same behavior for both cases?
source
share