亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

解碼 json 值的更好方法

解碼 json 值的更好方法

Go
MMTTMM 2023-07-17 14:29:29
假設一個具有通用格式的 JSON 對象  "accounts": [    {      "id": "<ACCOUNT>",       "tags": []    }  ]}我可以創建一個帶有相應 json 標簽的結構來像這樣解碼它 type AccountProperties struct {    ID AccountID `json:"id"`    MT4AccountID int `json:"mt4AccountID,omitempty"`    Tags []string `json:"tags"`  }  type Accounts struct {    Accounts []AccountProperties `json:"accounts"`  }但最后一個只有一個元素的結構對我來說似乎不正確。有沒有一種方法可以簡單地說,type Accounts []AccountProperties `json:"accounts"`而不是創建一個全新的結構來解碼這個對象?
查看完整描述

1 回答

?
叮當貓咪

TA貢獻1776條經驗 獲得超12個贊

您需要某個地方來存儲 json 字符串accounts。用一個:


var m map[string][]AccountProperties

就足夠了,盡管您當然需要知道使用字符串文字accounts來訪問由此創建的(單個)映射條目:


type AccountProperties struct {

? ? ID? ? ? ? ? ?string? ?`json:"id"`

? ? MT4AccountID int? ? ? `json:"mt4AccountID,omitempty"`

? ? Tags? ? ? ? ?[]string `json:"tags"`

}


func main() {

? ? var m map[string][]AccountProperties

? ? err := json.Unmarshal([]byte(data), &m)

? ? fmt.Println(err, m["accounts"])

}

D(我必須更改to的類型string并修復{json 中缺失的內容)。

這并不比僅使用匿名結構類型短:

var?a?struct{?Accounts?[]AccountProperties?}

就調用而言Unmarshall(這樣完成后使用起來更方便。如果您想在調用中使用這樣的匿名結構json.Marshall,則需要標記其單個元素以獲得小寫編碼:如果沒有標記,它將被調用"Accounts"而不是"accounts".

(我并不認為地圖方法更好,只是一種替代方法。)


查看完整回答
反對 回復 2023-07-17
  • 1 回答
  • 0 關注
  • 119 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號