得到:无法将字符串解组为Go值

问题描述

遇到一些麻烦,无法在go中将某些内容编组到struct对象中。基本上,我的结构定义为:

 type TheParam struct {
    Id       string `json:"id,string"`
    Provider string `json:"provider,string"`
}

现在,我有一个带字节的变量,如果我使fmt.Print(string(data)),则得到:

"{\"id\":\"some-id\",\"provider\":\"any-provider\"}"

以字节为单位的数据示例是:

34 123 92 34 105 100 92 34 58 92 34 103 105 116 104 117 98 45 100 97 115 104 45 97 99 99 101 115 115 92 34 44 92 34 112 114 111 118 105 100 101 114 92 34 58 92 34 103 105 116 104 117 98 92 34 125 34

而且,我正在使用以下方法进行编组:

if err = json.Unmarshal(data,&myParam); err != nil {
        redisLogger.WithError(err).Error("unmarshalling into interface")
    }

因此,现在得到:json: cannot unmarshal string into Go value of type TheParam。我想念什么?

解决方法

字符串本身是编码的json值,因此首先需要将其解码为string,然后将此值解码为struct:https://play.golang.org/p/qSOd1O9fOSQ

也请注意struct类型的已更改标签。您无需在标记中使用类型说明。它会自动为您定义。

,

字符串struct标记是多余的,因为您已经在struct中定义了类型。

这个游乐场应该可以工作:

https://play.golang.org/p/NixyNSHOK8w