英文:
Marshal float64 onto json in Go
问题
我在Go语言中有一个struct
,其中包含一个float64
字段。然而,当我将该字段的值编组到JSON对象时,它给我返回一个指数形式的数字。
根据我对类似问题的研究,我了解到在JSON对象中它将是一个数字,在Go语言中它将是一个float64
,然而我不太明白如何读取实际的数字而不是一个float64
。
这是我的代码示例。
http://play.golang.org/p/pR1B2oBKw2
它显示了一个具有相同值的字符串和float64
,我只想在我的JSON对象上正确显示float64
。
我在这个论坛上找到了类似的问题,但似乎没有一个直接的答案。它们对我来说都是一些变通方法,并且与反编组对象相关,而不是反之。
英文:
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
得分: 5
翻译结果如下:
简短版本,你不能。
长版本?创建你自己的类型!
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
}
英文:
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论