我需要使用浮点数解码JSON字符串,例如:
{"name":"Galaxy Nexus", "price":"3460.00"}
我使用下面的Golang代码:
package main
import (
"encoding/json"
"fmt"
)
type Product struct {
Name string
Price float64
}
func main() {
s := `{"name":"Galaxy Nexus", "price":"3460.00"}`
var pro Product
err := json.Unmarshal([]byte(s), &pro)
if err == nil {
fmt.Printf("%+v\n", pro)
} else {
fmt.Println(err)
fmt.Printf("%+v\n", pro)
}
}
当我运行它时,得到的结果是:
json: cannot unmarshal string into Go value of type float64
{Name:Galaxy Nexus Price:0}
我想知道如何使用convert类型解码JSON字符串。
答案相当简单。只需添加告诉JSON交互程序,它就是一个用float64编码的字符串,string
(请注意,我只更改了Price
定义):
package main
import (
"encoding/json"
"fmt"
)
type Product struct {
Name string
Price float64 `json:",string"`
}
func main() {
s := `{"name":"Galaxy Nexus", "price":"3460.00"}`
var pro Product
err := json.Unmarshal([]byte(s), &pro)
if err == nil {
fmt.Printf("%+v\n", pro)
} else {
fmt.Println(err)
fmt.Printf("%+v\n", pro)
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句