如何解码类型为从字符串转换为 float64 的 JSON [英] How to decode JSON with type convert from string to float64
本文介绍了如何解码类型为从字符串转换为 float64 的 JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要解码一个带有浮点数的 JSON 字符串,例如:
I need to decode a JSON string with the float number like:
{"name":"Galaxy Nexus", "price":"3460.00"}
我使用下面的 Golang 代码:
I use the Golang code below:
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
", pro)
} else {
fmt.Println(err)
fmt.Printf("%+v
", pro)
}
}
当我运行它时,得到结果:
When I run it, get the result:
json: cannot unmarshal string into Go value of type float64
{Name:Galaxy Nexus Price:0}
我想知道如何使用类型转换来解码 JSON 字符串.
I want to know how to decode the JSON string with type convert.
推荐答案
答案要简单得多.只需添加告诉 JSON interpeter 这是一个带有 ,string
的字符串编码的 float64(请注意,我只更改了 Price
定义):
The answer is considerably less complicated. Just add tell the JSON interpeter it's a string encoded float64 with ,string
(note that I only changed the Price
definition):
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
", pro)
} else {
fmt.Println(err)
fmt.Printf("%+v
", pro)
}
}
这篇关于如何解码类型为从字符串转换为 float64 的 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文