json编码的双精度控制



我正在用双精度值数组编码一个复杂的Map结构。高精度并不重要,输出大小是,所以我试图得到JSON工具(杰克逊在这种情况下)序列化双精度值使用提供的DecimalFormat。

下面是我最好的选择,但这失败了,因为对象映射器没有选择序列化器来编码数组:

class MyTest
{
  public class MyDoubleSerializer extends JsonSerializer<double[]>
  {
    public void serialize(double[] value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException
    {
      for (double d : value)
      {
        jgen.writeStartArray();
        jgen.writeRaw( df.format( d ) );
        jgen.writeEndArray();
      }
    }
  }
  @Test
  public void test1() throws Exception
  {
    ObjectMapper mapper = new ObjectMapper();
    SimpleModule module = new SimpleModule("MyModule", new Version(0, 1, 0, "alpha"));
    module.addSerializer(double[].class, new MyDoubleSerializer());
    mapper.registerModule(module);
    Map<String, Object> data = new HashMap<String, Object>();
    double[] doubleList = { 1.1111111111D, (double) (System.currentTimeMillis()) };
    data.put( "test", doubleList );
    System.out.print( mapper.writeValueAsString( data ));
  }
}

输出为:

{"测试":[1.1111111111,1.315143204964 e12汽油}

我要找的是:

{"测试":[1.32 e12汽油,1.11 e0]}

任何想法?

另外,我不喜欢不得不生成一个字符串,并写为原始-有我可以提供一个StringBuffer到十进制格式来做到这一点吗?

谢谢

通过借用Double的内置序列化器来解决这个问题。

这是一个有点hack,因为writeRaw()不关心上下文,不写数组成员之间的逗号,所以我正在转换Json写入器和调用它的writeValue()方法来处理这个。

奇怪的是,这在问题中的示例中不起作用(同样不会在序列化这些双精度对象时调用),但在我的真实世界中更复杂的对象上确实起作用。

享受……

public class JacksonDoubleArrayTest
{
    private DecimalFormat df = new DecimalFormat( "0.##E0" );
    public class MyDoubleSerializer extends org.codehaus.jackson.map.ser.ScalarSerializerBase<Double>
    {
        protected MyDoubleSerializer()
        {
            super( Double.class );
        }
        @Override
        public final void serializeWithType( Double value, JsonGenerator jgen, SerializerProvider provider, TypeSerializer typeSer ) throws IOException,
                JsonGenerationException
        {
            serialize( value, jgen, provider );
        }
        @Override
        public void serialize( Double value, JsonGenerator jgen, SerializerProvider provider ) throws IOException, JsonGenerationException
        {
            if ( Double.isNaN( value ) || Double.isInfinite( value ) )
            {
                jgen.writeNumber( 0 ); // For lack of a better alternative in JSON
                return;
            }
            String x = df.format( value );
            if ( x.endsWith( "E0" ) )
            {
                x = x.substring( 0, x.length() - 2 );
            }
            else if ( x.endsWith( "E1" ) && x.length() == 6 )
            {
                x = "" + x.charAt( 0 ) + x.charAt( 2 ) + '.' + x.charAt( 3 );
            }
            JsonWriteContext ctx = (JsonWriteContext)jgen.getOutputContext();
            ctx.writeValue();
            if ( jgen.getOutputContext().getCurrentIndex() > 0 )
            {
                x = "," + x;
            }
            jgen.writeRaw( x );
        }
        @Override
        public JsonNode getSchema( SerializerProvider provider, Type typeHint )
        {
            return createSchemaNode( "number", true );
        }
    }
    @SuppressWarnings("unchecked")
    private static Map<String, Object> load() throws JsonParseException, JsonMappingException, IOException
    {
        ObjectMapper loader = new ObjectMapper();
        return (Map<String, Object>)loader.readValue( new File( "x.json" ), Map.class );
    }
    @Test
    public void test1() throws JsonGenerationException, JsonMappingException, IOException
    {
        ObjectMapper mapper = new ObjectMapper();
        SimpleModule module = new SimpleModule( "StatsModule", new Version( 0, 1, 0, "alpha" ) );
        module.addSerializer( Double.class, new MyDoubleSerializer() );
        mapper.registerModule( module );
        String out = mapper.writeValueAsString( load() );
        // System.out.println( out.length() );
    }
}

最新更新