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 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab