Go Unmarshal JSON,但是将嵌套结构解组为字符串

时间:2018-04-24 16:06:36

标签: json go

给出以下JSON对象:

{
"a": 1,
"b": [1,2,3,4]
}

以下type

type Thing struct {
  A Int `json:"a"`
  B string `json:"b"
}

我想要阵列" b"在编组进入go时保持为JSON字符串。

我目前收到以下错误:

panic: json: cannot unmarshal array into Go struct field Thing.b of type string

1 个答案:

答案 0 :(得分:4)

将字段设置为json.RawMessage。它将按原样存储,无需解释(即"[1,2,3,4]"),作为一个字节片,可以很容易地转换为字符串。

如果您需要直接使用字符串,则必须在您的类型上实施json.Unmarshaler interface并自行进行转换。

相关问题