我正在try 解组一些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

playground demo

推荐答案

我想你要找的是encoding/json包装中的RawMessage型.

文档说明:

键入RawMessage[]字节

RawMessage是一个原始的编码JSON对象.它实现了编组拆分器和解组程序,可用于延迟JSON解码或预计算JSON编码.

下面是使用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:15foo:[123 32 34 102 111 111 34 58 32 49 50 51 44 32 34 98 97 114 34 58 34 98 97 122 34 32 125]}

Playground

Go相关问答推荐

如何在go中传递C函数指针

无法在Macos上使用Azure Speech golang SDK

在Go中根据命名空间/字符串生成UUID

Go:拆分一个由逗号分隔的键/值对字符串,并在给定的键/价值对中嵌入可能的逗号

Go 1.20 中如何计算连接错误?

从 wincrypt API 到 Go 的 RC2 解密

Golang Fiber Render - 将数据发送到多个布局

当我使用 CircleCI 构建 Go Image 时,我得到runtime/cgo: pthread_create failed: Operation not allowed

使用golang sqlc中的引用参数

Exchange Web 服务 - 使用 soap xml 请求查找所有未读邮件

如何使用名称具有包名称的嵌套 struct 启动 go struct

致命错误:找不到由 zergon321/reisen 引起的libavcodec/avcodec.h文件

如何修改go gin的默认端口?我的 8080 端口正在使用中

如何将文件上传到 Google Drive,并与使用服务帐户和 Golang 的任何人共享

如何将多个切片打印为一个切片?

如何使用特定的 Go 版本运行 govulncheck?

如何使用 math/big 对 bigInt 进行取模?

在 Golang 中获取谷歌云服务帐户的访问令牌?

退格字符在围棋操场中不起作用

即使没有竞争条件也没有得到任何输出