簡體   English   中英

如何在結構內部解組多維數組

[英]How to unmarshal multi dimensional array inside struct

我有以下數據:

{"me":[{"id": "0xcfd","Title":"Story of Stackoverflow","Users":[{"id":"1","Name":"MetaBoss"},{"id":"2","Name":"Owner"}],"Tag":"golang,programming"}]}

而且我有以下結構:

type Root struct {
    ID string `json:"id,omitempty"`
    Title string `json:"Title,omitempty"`
    Myuser Users `json:"Users,omitempty"` // Users is struct
    Tag string `json:"Tag,omitempty"`
}

type Users struct {
    ID string `json:"id,omitempty"`
    Name string `json:"Name,omitempty"`
}

為了解組數據,我正在嘗試執行以下操作-

type Unmarh struct {
    Me []Root `json:"me"`
}

var r Unmarh
err = json.Unmarshal(response, &r)

在打印r.Me[0].Myuser ,我無法獲取數據。

我遇到錯誤-

json: cannot unmarshal array into go struct field Root.Myuser of type User struct {....Users struct data}

它需要Myuser是多維array類型,而不是Users結構。 我不知道如何在struct內表示Users multidimensional array

在json中, Users鍵是一個數組,因此對應的Go字段應為切片。

type Root struct {
    ID    string `json:"id,omitempty"`
    Title string `json:"Title,omitempty"`
    Users []User `json:"Users,omitempty"`
    Tag   string `json:"Tag,omitempty"`
}

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

暫無
暫無

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

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