Reputation: 9154
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?
Upvotes: 3
Views: 14115
Reputation: 116522
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);
Upvotes: 0
Reputation: 279990
You can register the JsonSerializer
for the primitive type double
.
module.addSerializer(double.class, new DoubleSerializer());
Upvotes: 15