Jackson序列化器用于原始类型 [英] Jackson serializer for primitive types
本文介绍了Jackson序列化器用于原始类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在编写一个自定义序列化程序,将双值转换为JSON对象中的字符串。到目前为止我的代码:
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);
}
}
这适用于Double(班级成员),但不适用于双(原始类型)成员。例如,
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;
}
}
返回:{x:1111142143543543565865975808, y:1.1111421435435436E27}
Returns: {"x":"1111142143543543565865975808","y":1.1111421435435436E27}
是否有办法让两种情况都遵循相同的行为?
Is there a way to make it follow same behavior for both cases?
推荐答案
您可以为基本类型 double
注册 JsonSerializer
。
You can register the JsonSerializer
for the primitive type double
.
module.addSerializer(double.class, new DoubleSerializer());
这篇关于Jackson序列化器用于原始类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文