我正在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从map.dbf map.prj map.shp map.shx中的任何文件中了解层名称

如何获得与cksum相同的CRC 32?

gorm如何声明未自动更新的unix时间戳米尔斯字段

map 中的多个函数类型,Golang

Go源在Goland(IDEA)中以灰色显示.什么意思?我怎么才能让它恢复正常?

Go:为什么我不能比较 net.Addr

如何找到一个空闲的TPM句柄来保存新的密钥对对象?

如何根据地址和大小打印字符串

如何将字节文件高效地读入int64切片?

在 Go 中使用 Apache Arrow 按时间间隔对事件进行分区

xml.Unmarshal 不支持的类型 struct

如何在 Golang 中打印 2 列表?

Get 请求在 Thunder 客户端/Postman 中返回数据,但在 Golang 代码中给出空白数据

转换朴素递归硬币问题时的记忆错误

Wire google Inject with multi return from provider 函数

获取切片元素的地址是否意味着 Go 中元素的副本?

在恒等函数中将类型 T 转换为类型 U

如何在 helm 中将字符串连接到 .AsConfig 的结果?

通用函数与外部包中的常见成员一起处理不同的 struct ?

正则表达式处理数字签名的多个条目