背景
当遇到请求的api返回数据结构中,部分字段的类型不能确定时,可以在定义结构体该字段时,指定其类型为json.RawMessage,
这样当从api取返回数据时,json.Unmarshal后,该字段仍然是[]byte类型,而我们可以对这一个字段再做针对性的处理。
/*
{
“type”:“File”,
“data”:{
“filename”:“this is a file”
}
}
{
“type”:“Persons”,
“data”:[{
“age”:12,
“sex”:1
},
{
“age”:11,
“sex”:2
}]
}
//如api返回的结构中,data字段可能是上边这两种
*/
代码
package jsonPrac
import "encoding/json"
type Response struct {
Type string
Data json.RawMessage
}
type File struct {
FileName string
}
type Person struct {
Age int
Sex int
}
type Persons []*Person
func PPP(input string) {
ss := Response{}
if err := json.Unmarshal([]byte(input), &ss); err != nil {
panic(err)
}
switch ss.Type {
case "File":
var f File
if err := json.Unmarshal(ss.Data, &f); err != nil {
panic(err)
}
println(f.FileName)
case "Persons":
var p Persons
if err := json.Unmarshal(ss.Data, &p); err != nil {
panic(err)
}
println(p[0].Age)
}
}
//main.go
func main() {
input :=`{"type": "File","data": {"filename": "for test"}}`
input1 :=`{"type": "Persons","data": [{"age": 12, "sex":10},{"age":100, "sex":99}]}`
jsonPrac.PPP(input)
jsonPrac.PPP(input1)
}
输出
for test
12