获取:无法将字符串解组为 Go 值
getting: Cannot unmarshal string into Go value
我在将一些内容解组到 go 中的结构对象时遇到了一些麻烦。基本上,我的结构定义为:
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
,然后将此值解码为结构:https://play.golang.org/p/qSOd1O9fOSQ
另外请注意struct类型变化的标签。您不需要在标记中使用类型规范。它将自动为您定义。
我在将一些内容解组到 go 中的结构对象时遇到了一些麻烦。基本上,我的结构定义为:
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
,然后将此值解码为结构:https://play.golang.org/p/qSOd1O9fOSQ
另外请注意struct类型变化的标签。您不需要在标记中使用类型规范。它将自动为您定义。