dpd20130 2015-08-19 01:51
浏览 98
已采纳

在Go中将float64封送至json

I have a struct in go which contains a float64 field. However when I marshal the value of this field onto a json object it gives me a exponential number. Based on my research on people with similar issues here, I understand that in json objects it will be number and in go it will be a float64, however I don't quite understand how to read the actual number and not a float64. Here's a sample of my code.

http://play.golang.org/p/pR1B2oBKw2

It shows a string and a float64 both with the same values and all I want is the float64 to be dislpayed correctly on my json object. I have found similar questions on this forum but none of them seems to have a straight forward answer. They all seems to be workarounds to me and are related to unmarshaling an object and not the other way around.

  • 写回答

1条回答 默认 最新

  • douzhuang1900 2015-08-19 02:08
    关注

    Short version, you can't.

    Long version? create your own type!

    type FloatString float64
    
    func (fs FloatString) MarshalJSON() ([]byte, error) {
        vs := strconv.FormatFloat(float64(fs), 'f', 2, 64)
        return []byte(`"` + vs + `"`), nil
    }
    
    func (fs *FloatString) UnmarshalJSON(b []byte) error {
        if b[0] == '"' {
            b = b[1 : len(b)-1]
        }
        f, err := strconv.ParseFloat(string(b), 64)
        *fs = FloatString(f)
        return err
    }
    

    <kbd>playground</kbd>

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 机器学习简单问题解决
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写