json.Unmarshal 嵌套对象成字符串或 []byte

标签 json go unmarshalling

我正在尝试解码一些 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

最佳答案

我认为您正在寻找的是 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]}

Playground

关于json.Unmarshal 嵌套对象成字符串或 []byte,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20101954/

相关文章:

javascript - 在 AJAX 自动完成中操作 JSON

java - org.json.JSONObject 无法转换为 JSONArray

Javascript/Json 日期转换问题

GORM协会

java - 从java Map生成Json

amazon-web-services - 使用 golang 检索 dynamodb 中的最新记录

string - GO标志pkg读取包含诸如“\u00FC”之类的转义 rune 的选项字符串将不会读取

go - 在 Go 中解码为结构时的奇怪行为

java - 使用 JAXB 解码

java - 使用 JAXB 并根据封闭标签以不同方式解释相同标签