有很多方法可以构造它,但是最简单的技术归结为实现
json.Unmarshaler和检查数据类型。您可以最少地解析json字节,通常只是第一个字符,或者您可以尝试解组每种类型并返回成功的类型。
我们将在此处使用后一种技术,并将ResourceData插入切片中,而不管传入数据的格式如何,因此我们始终可以以相同的方式对其进行操作:
type Resource struct { Data []ResourceData}func (r *Resource) UnmarshalJSON(b []byte) error { // this gives us a temporary location to unmarshal into m := struct { DataSlice struct { Data []ResourceData `json:"data"` } DataStruct struct { Data ResourceData `json:"data"` } }{} // try to unmarshal the data with a slice err := json.Unmarshal(b, &m.DataSlice) if err == nil { log.Println("got slice") r.Data = m.DataSlice.Data return nil } else if err, ok := err.(*json.UnmarshalTypeError); !ok { // something besides a type error occurred return err } // try to unmarshal the data with a struct err = json.Unmarshal(b, &m.DataStruct) if err != nil { return err } log.Println("got struct") r.Data = append(r.Data, m.DataStruct.Data) return nil}http://play.golang.org/p/YIPeYv4AfT



