我需要解码带有 float 的 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 解释器它是带有 ,string
的字符串编码 float64(请注意,我只更改了 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)
}
}
https://stackoverflow.com/questions/9452897/