2014-09-20 88 views
1

我正在编写一个自定义序列化器,以将double值转换为JSON对象中的字符串。到目前为止我的代码:基本类型的Jackson序列化器

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

这工作完全正常双(类成员),但双(基本型)的成员不起作用。例如,

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}

有没有一种方法,使其遵循相同的行为,对于两种情况?

回答

10

您可以为原始类型double注册JsonSerializer

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

哇!不能相信我在这上面失去了一个小时:)谢谢! – mihsathe 2014-09-20 04:06:24

-1

你可以用自定义序列化程序来做,但有一个更简单的方法。 启用JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS

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

我认为这是在v2.3中添加的。我只限于2.2。 – mihsathe 2014-09-24 22:28:15

+0

我刚刚测试过它:你仍然得到科学记数法 – Chris 2016-11-30 17:27:52

+0

其实这可能是真的......因为它只是引用数字。不幸的是,虽然有'JsonGenerator.Feature.WRITE_BIGDECIMAL_AS_PLAIN',只影响'BigDecimals'而不是'double's或'float's。可能有意义提出一个问题,为非BigDecimal浮点值添加单独的JsonGenerator.Feature。 – StaxMan 2016-11-30 23:43:49

相关问题