简体   繁体   English

去解组JSON,但解组嵌套结构作为字符串

[英]Go Unmarshal JSON, but unmarshal nested structure as a string

Given the following JSON object: 给定以下JSON对象:

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

And the following type : 和以下type

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

I would like the Array "b" to stay as a JSON string when marshalled into go. 我希望将数组“ b”编组后保留为JSON字符串。

I currently get the following error: 我目前收到以下错误:

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

Set the field as a json.RawMessage . 将字段设置为json.RawMessage It'll be stored as is, without interpretation (ie. as "[1,2,3,4]" ), as a slice of bytes, which can be converted to a string easily enough. 它会按原样存储,不做任何解释(即作为"[1,2,3,4]" )存储为一个字节片,可以很容易地将其转换为字符串。

If you need a string directly, you'll have to implement the json.Unmarshaler interface on your type and do the conversion yourself. 如果直接需要字符串,则必须在类型上实现json.Unmarshaler接口 ,然后自己进行转换。

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

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