我正在尝试解码一些 json,以便嵌套对象不会被解析,而只是被视为 string
或 []byte
。
所以我想得到以下内容:
{
"id" : 15,
"foo" : { "foo": 123, "bar": "baz" }
}
解码为:
type Bar struct {
ID int64 `json:"id"`
Foo []byte `json:"foo"`
}
我收到以下错误:
json: cannot unmarshal object into Go value of type []uint8
最佳答案
我认为您正在寻找的是 RawMessage输入 encoding/json
包。
文档说明:
type RawMessage []byte
RawMessage is a raw encoded JSON object. It implements Marshaler and Unmarshaler and can be used to delay JSON decoding or precompute a JSON encoding.
这是一个使用 RawMessage 的工作示例:
package main
import (
"encoding/json"
"fmt"
)
var jsonStr = []byte(`{
"id" : 15,
"foo" : { "foo": 123, "bar": "baz" }
}`)
type Bar struct {
Id int64 `json:"id"`
Foo json.RawMessage `json:"foo"`
}
func main() {
var bar Bar
err := json.Unmarshal(jsonStr, &bar)
if err != nil {
panic(err)
}
fmt.Printf("%+v\n", bar)
}
输出:
{Id:15 Foo:[123 32 34 102 111 111 34 58 32 49 50 51 44 32 34 98 97 114 34 58 32 34 98 97 122 34 32 125]}
关于json.Unmarshal 嵌套对象成字符串或 []byte,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20101954/