如何將數(shù)據(jù)解組到地圖中?JSON 是一個(gè)對(duì)象列表,我想在解組過程中將其轉(zhuǎn)換為地圖。但是,初始化地圖似乎會(huì)創(chuàng)建一個(gè)未正確返回的新對(duì)象。type foo struct { Id string `json:"id"` Name string `json:"name"`}type fooList []*footype fooMap map[string]*foofunc (f fooMap) UnmarshalJSON(data []byte) error { f := fooMap{} // required since map is not initialized var results fooList if err := json.Unmarshal(data, &results); err != nil { return err } for i := 0; i < len(results); i++ { result := results[i] f[result.Id] = result } return nil}我已經(jīng)檢查以確保沒有錯(cuò)誤并且地圖在 Unmarshal 函數(shù)的末尾包含正確的值,但是當(dāng)我查看結(jié)果應(yīng)該被解組到的對(duì)象時(shí),它是空的。下面是我如何解組父對(duì)象,它是包含 fooMaps 的結(jié)構(gòu)片段。type bar struct { Foos fooMap `json:"foos"`}type bars []*bar...var results barsif err := json.Unmarshal(data, &results); err != nil { return err}// here results contains a single bar item (which is correct) but the Foos// property does not exist at all我還嘗試更改Foos為類型*fooMap,然后將解組函數(shù)更新為,func (f *fooMap) UnmarshalJSON(...)但從未調(diào)用解組函數(shù)。
- 1 回答
- 0 關(guān)注
- 166 瀏覽
添加回答
舉報(bào)
0/150
提交
取消