
如果实现json.Unmarshaler,则可以定义一个将每种项目类型解析为相关结构的结构。
例:
// Dynamic represents an item of any type.type Dynamic struct { Value interface{}}// UnmarshalJSON is called by the json package when we ask it to// parse something into Dynamic.func (d *Dynamic) UnmarshalJSON(data []byte) error { // Parse only the "type" field first. var meta struct { Type string } if err := json.Unmarshal(data, &meta); err != nil { return err } // Determine which struct to unmarshal into according to "type". switch meta.Type { case "product": d.Value = &Product{} case "post": d.Value = &Post{} default: return fmt.Errorf("%q is an invalid item type", meta.Type) } return json.Unmarshal(data, d.Value)}// Product and Post are structs representing two different item types.type Product struct { Name string Price int}type Post struct { Title string Content string}用法:
func main() { // Parse a JSON item into Dynamic. input := `{ "type": "product", "name": "iPhone", "price": 1000 }` var dynamic Dynamic if err := json.Unmarshal([]byte(input), &dynamic); err != nil { log.Fatal(err) } // Type switch on dynamic.Value to get the parsed struct. // See https://tour.golang.org/methods/16 switch dynamic.Value.(type) { case *Product: log.Println("got a product:", dynamic.Value) case *Post: log.Println("got a product:", dynamic.Value) }}输出:
2009/11/10 23:00:00得到了一个产品:&{iPhone 1000}
在Go Playground中尝试一下。
提示:如果您有动态对象列表,只需将其解析为
Dynamic:
var items []Dynamicjson.Unmarshal(`[{...}, {...}]`, &items)输出示例:
[&{iPhone 1000}&{A Good Post Lorem ipsum …}]
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)