douhuan1257 2013-11-20 14:59
浏览 30

Go是否正确将float64编组为JSON?

Using go1.1.2 Win64, I have a Go program that "marshal"'s a struct containing a float64. When the value of the float64 is not a whole number eg. 1234.44, then it gets "marshal"ed as a float (json.Marshal). When however it is a whole number eg. "1234.00" it is marshalled as an integer"1234". When I receive that at the other end (Dart), Dart (30188) treats the whole number as an integer (in map - JSON.decode). Consequently the Dart program aborts when the representation of the float (double) data doesn't contain a decimal point, and I attempt to "extract" it from the map as a double.

This can obviously be solved a number of different ways (eg. convert to integer and then convert back to float), however I wondered if there is another (better) way to handle this situation.

Is there another better way to handle this than to convert float64 to integer?

  • 写回答

2条回答 默认 最新

  • dongli5785 2013-11-20 15:45
    关注

    JSON, just like Javascript, doesn't differ between integers and numbers.

    If Dart treats 1234.00 differently from 1234, then it is making assumptions about the value not supported by the JSON specification.

    While Go does indeed marshal float64 correctly, one way of getting around the problem with Dart's assumption is by implementing the Marshaler interface on your own type:

    type Number float64
    
    func (n Number) MarshalJSON() ([]byte, error) {
        // There are probably better ways to do it. It is just an example
        return []byte(fmt.Sprintf("%f", n)), nil
    }
    

    And then you can use your own Number type, instead of float64, in the structs that you will Marshal. This way you can make sure that your numbers will always be marshaled with a decimal point.

    Working example on Playground

    评论

报告相同问题?

悬赏问题

  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大