我正在处理第三方基于 JSON 的 API。通常它将所有数字括在引号中,但有时不会。我对此无能为力。
我正在尝试提出一个解决方案,无论它们是否被引用,它都会解析数字。标准库提供了一个,string字段标签,它允许将数字字段映射到加引号的值,但不幸的是,如果它不在引号中,它就无法处理该值。
func test(s string) {
err := json.Unmarshal([]byte(s), &struct {
F1 float64
F2 float64 `json:",string"`
}{})
if err != nil {
fmt.Println(err)
return
}
fmt.Println("success")
}
func main() {
test(`{"f1": 1.23}`) // success
test(`{"f1": "1.23"}`) // cannot unmarshal string into Go value of type float64
test(`{"f2": 1.23}`) // invalid use of ,string struct tag, trying to unmarshal unquoted value into ...
test(`{"f2": "1.23"}`) // success
}
有没有解决的办法?
翻阅古今
相关分类