Unmarshal Inconsistent JSON in Go

旧巷老猫 提交于 2019-12-06 11:58:16

问题


I'm working with JSON that returns three different object types 'items','categories' and 'modifiers'. An example of the JSON can be viewed here. I created models for the three types of objects. But when I unmarshal I have selected one of the types to unmarshal the entire JSON to.(I know this cant be the correct way...) I then try to parse out the different items depending on what their type is identified as in the json field 'Type' and then append that object to a slice of the proper type. I am having errors because I don't know how to unmarshal JSON that has different types in it that have different fields.

What is the proper method to unmarshal JSON that contains different objects, each with their own respective fields?

Is the solution to create a "super model" which contains all possible fields and then unmarshal to that?

I'm still fairly new and would appreciate any advice. Thanks!


回答1:


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...}]




回答2:


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



来源:https://stackoverflow.com/questions/54836933/unmarshal-inconsistent-json-in-go

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