簡體   English   中英

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

[英]json.Unmarshal nested object into string or []byte

我正在嘗試解組一些 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

游樂場演示

我認為您正在尋找的是encoding/json包中的RawMessage類型。

該文檔指出:

輸入 RawMessage [] 字節

RawMessage 是一個原始編碼的 JSON 對象。 它實現了 Marshaler 和 Unmarshaler,可用於延遲 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: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]}

操場

Foo 類型是 map[string]string 所以正確定義 Foo :

type Bar struct {
    id int64
    Foo map[string]string
}

認為這樣會更好

定義實現Unmarshaler接口的類型使您可以訪問正在解析的[]byte

type Prefs []byte

func (p *Prefs) UnmarshalJSON(b []byte) error {
    *p = make(Prefs, len(b))
    copy(*p, b)
    return nil
}

游樂場演示

經過一番修補后,我發現在您的游樂場演示中,最大的問題是將 json 類型轉換為 []byte。 要了解我的意思,請看一下這個游樂場: http ://play.golang.org/p/M0706KCZbh

如果你運行它,你會注意到 typecast slice 和 marshaled slice 之間的 []byte 在 'Prefs' 變量的點附近不同。

從結構封送的 json

[123 34 105 100 34 58 49 53 44 34 112 114 101 102 115 34 58 34 101 121 65 105 90...

類型轉換 [] 字節

[123 34 105 100 34 58 49 53 44 34 112 114 101 102 115 34 58 123 34 102 111 111 34...

我已經刪除了空白以嘗試使其盡可能對齊。 主要的收獲是,類型轉換不會產生與通過 json.Marshal 方法運行數據相同的結果,並且要使這項工作正常工作,您需要一個自定義類型來處理 json 包無法識別的內容的解組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM