2 回答
TA贡献1773条经验 获得超3个赞
查看文档中的“json - raw Message” ,从那里开始,您可以根据需要尝试解析它。
package main
import (
"encoding/json"
"fmt"
"log"
"strconv"
"unicode/utf8"
)
type Person struct {
Name string `json:"name"`
Age json.RawMessage `json:"age"`
}
func main() {
var j = []byte(`{"name": "Joe","age": "42"}`)
var j2 = []byte(`{"name": "Joe","age": 42}`)
stringOrInt(j)
stringOrInt(j2)
}
func stringOrInt(bytes []byte) {
var p Person
err := json.Unmarshal(bytes, &p)
if err != nil {
log.Fatal(err)
}
if utf8.Valid(p.Age) {
i, err := strconv.Atoi(string(p.Age))
if err != nil {
fmt.Println("got int " + strconv.Itoa(i))
} else {
fmt.Println("got string")
}
} else {
fmt.Println("whoops")
}
}
TA贡献1783条经验 获得超4个赞
package main
import (
"encoding/json"
"fmt"
"strconv"
)
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
}
func (p *Person) UnmarshalJSON(b []byte) error {
var objMap map[string]*json.RawMessage
err := json.Unmarshal(b, &objMap)
if err != nil {
return err
}
var name string
err = json.Unmarshal(*objMap["name"], &name)
if err != nil {
return err
}
var ageInt int
err = json.Unmarshal(*objMap["age"], &ageInt)
if err != nil {
// age is string
var ageString string
err = json.Unmarshal(*objMap["age"], &ageString)
if err != nil {
return err
}
aI, err := strconv.Atoi(ageString)
if err != nil {
return err
}
p.Age = aI
} else {
p.Age = ageInt
}
p.Name = name
fmt.Printf("%+v", *p)
return nil
}
func main() {
p := `{"name": "John", "age": "10"}`
// p := `{"name": "John", "age": 10}`
newP := Person{}
err := newP.UnmarshalJSON([]byte(p))
if err != nil {
fmt.Printf("Error %+v", err)
}
}
https://play.golang.org/p/AK8H_wdNqmt
你可以尝试这样的事情。尝试读取并解析 Into int,如果无法检查字符串值,则将其解析为 int,然后将 int 值分配给 person struct
- 2 回答
- 0 关注
- 118 浏览
添加回答
举报