如何在Golang中将类型从字符串转换为float64解码JSON?
我需要使用浮点数解码JSON字符串,例如:
{"name":"Galaxy Nexus", "price":"3460.00"}我使用下面的Golang代码:
package mainimport (
    "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 mainimport (
    "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)
    }
}
以上是 如何在Golang中将类型从字符串转换为float64解码JSON? 的全部内容, 来源链接: utcz.com/qa/404723.html








