简体   繁体   English

如何修复 json:无法将 object 解组为 []json.RawMessage 类型的 Go 值

[英]How to fix json: cannot unmarshal object into Go value of type []json.RawMessage

I want to unmarshal我想解组

var j = []byte(`[{"major":1},{"minor":0}]`)

into进入

type Version struct {
    Major int `json:"major"`
    Minor int `json:"minor"`
}

using custom unmarshaler by looping the inner slice:通过循环内部切片使用自定义解组器:

func (h *Version) UnmarshalJSON(b []byte) error {
    var wrapper []json.RawMessage

    err := json.Unmarshal(b, &wrapper)
    if err == nil {
        for _, v := range wrapper {
            if err = json.Unmarshal(v, &h); err != nil {
                break
            }
        }
    }

    return err
}

The inner UnmarshalJSON triggers内部UnmarshalJSON触发器

json: cannot unmarshal object into Go value of type []json.RawMessage

which is strange because the target is a *Version .这很奇怪,因为目标是*Version What is wrong here?这里有什么问题? Play: https://play.golang.org/p/Av59IkYTioS播放: https://play.golang.org/p/Av59IkYTioS

The "inner" unmarshal call will recursively call Version.UnmarshalJSON() : “内部”解组调用将递归调用Version.UnmarshalJSON()

json.Unmarshal(v, &h)

And your error comes from the recursive call: you try to unmarshal {"major":1} into []json.RawMessage .您的错误来自递归调用:您尝试将{"major":1}解组为[]json.RawMessage

You do not want to call Version.UnmarshalJSON() recursively, so create a new type that strips all methods, including the UnmarshalJSON() :您不想递归调用Version.UnmarshalJSON() ,因此创建一个新类型来剥离所有方法,包括UnmarshalJSON()

    type version Version
    h2 := (*version)(h)
    for _, v := range wrapper {
        if err = json.Unmarshal(v, &h2); err != nil {
            break
        }
    }

With this change it works, and adding fmt.Println(msg) the output will be (try it on the Go Playground ):通过此更改,它可以工作,并添加fmt.Println(msg) output 将是(在Go Playground上尝试):

<nil>
{1 0}

Normally this would cause a stack overflow error, but since your second call errors, the recursion breaks.通常这会导致堆栈溢出错误,但由于您的第二次调用错误,递归中断。 See related: Call json.Unmarshal inside UnmarshalJSON function without causing stack overflow相关见: Call json.Unmarshal inside UnmarshalJSON function 而不会导致堆栈溢出

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM