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>

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

报告相同问题?