我正在使用通常提供 json 字符串值的 API,但它们有时会提供数字。例如,99% 的时间是这样的:
{
"Description": "Doorknob",
"Amount": "3.25"
}
但无论出于何种原因,有时它是这样的:{
"Description": "Lightbulb",
"Amount": 4.70
}
这是我正在使用的结构,它在 99% 的时间内都有效:type Cart struct {
Description string `json:"Description"`
Amount string `json:"Amount"`
}
但是当他们提供数字量时它会中断。解码结构时类型检查的最佳方法是什么?游乐场:https://play.golang.org/p/S_gp2sQC5-A
最佳答案
对于一般情况,您可以使用 interface{}
如 Burak Serdar's answer 中所述.
对于数字,有 json.Number
type:它接受 JSON 数字和 JSON 字符串,如果它以字符串形式给出,它可以“自动”解析数字 Number.Int64()
或 Number.Float64()
.不需要自定义编码器/解码器。
type Cart struct {
Description string `json:"Description"`
Amount json.Number `json:"Amount"`
}
测试它:var (
cart1 = []byte(`{
"Description": "Doorknob",
"Amount": "3.25"
}`)
cart2 = []byte(`{
"Description": "Lightbulb",
"Amount": 4.70
}`)
)
func main() {
var c1, c2 Cart
if err := json.Unmarshal(cart1, &c1); err != nil {
panic(err)
}
fmt.Printf("%+v\n", c1)
if err := json.Unmarshal(cart2, &c2); err != nil {
panic(err)
}
fmt.Printf("%+v\n", c2)
}
输出(在 Go Playground 上尝试):{Description:Doorknob Amount:3.25}
{Description:Lightbulb Amount:4.70}
关于json - 在 Go 中解码时输入检查 json 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64040825/