将json.Unmarshal嵌套对象转换为字符串或[]字节 [英] json.Unmarshal nested object into string or []byte

查看:199
本文介绍了将json.Unmarshal嵌套对象转换为字符串或[]字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图对一些json进行解组,以便嵌套对象不会被解析,而只是作为字符串 [] byte



所以我想得到以下结果:

  {
id:15,
foo:{foo:123,bar:baz}
}

解组为:

 类型Bar struct {
Id int64`json:id`
Foo [] byte`json:foo`
}

我得到以下错误:

  json:can not unmarshal object进入Go类型的值[] uint8 

playground demo

解决方案

我认为你要找的是> RawMessage 类型在编码/ json 包中。



文件指出:


输入RawMessage [] byte



RawMessage是原始编码的JSON对象。它实现了Marshaler和Unmarshaler,可用于延迟JSON解码或预先计算JSON编码。

以下是使用RawMessage :

  package main 

import(
encoding / json
fmt


var jsonStr = [] byte(`{
id:15,
foo:{foo:123, bar:baz}
}`)

类型结构体{
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]}

游乐场


I'm trying to Unmarshal some json so that a nested object does not get parsed but just treated as a string or []byte.

So I want to get the following:

{
    "id"  : 15,
    "foo" : { "foo": 123, "bar": "baz" }
}

Unmarshaled into:

type Bar struct {
    Id  int64  `json:"id"`
    Foo []byte `json:"foo"`
}

I get the following error:

json: cannot unmarshal object into Go value of type []uint8

playground demo

解决方案

I think what you are looking for is the RawMessage type in the encoding/json package.

The documentation states:

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.

Here is a working example of using 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)
}

Output:

{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嵌套对象转换为字符串或[]字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆