java - Jackson serializer for primitive types -
i writing custom serializer convert double values strings in json objects. code 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 fine double (class members) not work double (primitive type) members. 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 way make follow same behavior both cases?
you can register jsonserializer
primitive type double
.
module.addserializer(double.class, new doubleserializer());
Comments
Post a Comment