Unmarshal Inconsistent JSON in Go

五迷三道 提交于 2019-12-04 15:32:30

If you implement json.Unmarshaler, you can define a struct that parses each item type into it's relevant struct.

Example:

// 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
}

Usage:

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)
    }
}

Output:

2009/11/10 23:00:00 got a product: &{iPhone 1000}

Try it in the Go Playground.


Tip: if you have a list of dynamic objects, just parse into a slice of Dynamic:

var items []Dynamic
json.Unmarshal(`[{...}, {...}]`, &items)

Example output:

[&{iPhone 1000} &{A Good Post Lorem ipsum...}]

I think https://github.com/mitchellh/mapstructure also fits into your use case.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!