bj_lmj 2013-08-08 15:22 采纳率: 0%
浏览 566
已采纳

Gson转json的时候double处理少了个0

Gson 转json 的时候 0.00 会转成0.0 ,有没有方式让它转正确,或者转为“0.00” 也可以

  • 写回答

2条回答

  • FangXingXing007 2013-08-09 09:26
    关注

    可以在GsonBuilder中注册typeAdapter,定制序列化double的过程
    [code="java"]
    private static final GsonBuilder builder=new GsonBuilder();
    builder.registerTypeAdapter(Double.class, new DoubleTypeAdapter());
    Gson gson=builder.create();

    [/code]
    TypeAdapter的实现如下
    [code="java"]

    class DoubleTypeAdapter implements JsonSerializer{

    @Override
    public JsonElement serialize(Double d, Type type,
            JsonSerializationContext context) {
        DecimalFormat format=new DecimalFormat("##0.00");
        String temp=format.format(d);
        System.out.println(temp);
        JsonPrimitive pri=new JsonPrimitive(temp);
        return pri;
    }
    

    }
    [/code]

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?