在Go中解组不一致的JSON

问题描述 投票:2回答:2

我正在使用JSON,它返回三种不同的对象类型'items','categories'和'modifiers'。 An example of the JSON can be viewed here.我为三种类型的物体创建了模型。但是当我解组时,我选择了一种类型来解组整个JSON。(我知道这不能是正确的方法......)然后我尝试解析不同的项目,具体取决于它们的类型被识别为json字段'Type'然后将该对象附加到正确类型的切片。我有错误,因为我不知道如何解组具有不同字段的不同类型的JSON。

解组包含不同对象的JSON的正确方法是什么,每个对象都有各自的字段?

解决方案是创建一个“超级模型”,其中包含所有可能的字段,然后解组吗?

我仍然相当新,并会感激任何建议。谢谢!

json go unmarshalling
2个回答
3
投票

如果实现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}

Try it in the Go Playground


提示:如果您有一个动态对象列表,只需解析为一片Dynamic

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

示例输出:

[IPhone和{1000}和{...}好的帖子Lorem存有]


1
投票

我认为https://github.com/mitchellh/mapstructure也适合您的用例。

© www.soinside.com 2019 - 2024. All rights reserved.