是否可以在 Go 中添加嵌套的 json "as is"?

Is it possible to add a nested json "as is" in Go?

是否可以通过这种方式添加嵌套 json "as is"。嵌套的 json 没有任何结构,可能有所不同。我需要将嵌套的 json 数据直接放到根节点。

https://play.golang.org/p/MzBt7DLQEpD

type RootJson struct {
    NestedJson []byte
    AdditionalField string
}

func main() {
    nestedJson := []byte("{\"number\": 1, \"string\": \"string\", \"float\": 6.56}")

    rootJson := RootJson{nestedJson, "additionalField"}
    payload, _ := json.Marshal(&rootJson)

    fmt.Println(string(payload))

}

是的,这是可能的。使用实现自定义编组/解组的 json.RawMessage 类型,"renders" 它按原样进入 JSON 输出。这只是一个普通的字节切片:

type RawMessage []byte

它的值应该是原始 JSON 文本的 UTF-8 编码字节序列(正是你进行转换时得到的,例如 []byte("someText"))。

type RootJson struct {
    NestedJson      json.RawMessage
    AdditionalField string
}

有了这个,输出将是(在 Go Playground 上试试):

{"NestedJson":{"number":1,"string":"string","float":6.56},
    "AdditionalField":"additionalField"}

(缩进是我加的。)