basicMap[key] = value我有以下最小復制,當此代碼運行時,它會在because處引發例外assignment to entry in nil map,但是它僅在型別為[]CustomMap時才會這樣做 - 當我將 aCustomMap用于單個專案時,它作業得很好。
有沒有辦法在 go 中解組自定義物件陣列?
package main
import "encoding/json"
type CustomMap map[string]any
type Payload struct {
Items []CustomMap `json:"items"`
}
func mapToBasicMap(basicMap CustomMap, aMap map[string]any) {
for key, value := range aMap {
basicMap[key] = value
}
}
func (this CustomMap) UnmarshalJSON(data []byte) error {
var aMap map[string]any = make(map[string]any)
json.Unmarshal(data, &aMap)
mapToBasicMap(this, aMap)
return nil
}
func main() {
payload := Payload{}
json.Unmarshal([]byte("{\"items\":[{\"item1\": 1}]}"), &payload)
}
uj5u.com熱心網友回復:
Unmarshal 應該有一個指標接收器。在使用分配給它的值之前制作目標地圖。
func (this *CustomMap) UnmarshalJSON(data []byte) error {
var aMap map[string]any = make(map[string]any)
json.Unmarshal(data, &aMap)
*this = make(CustomMap)
mapToBasicMap(*this, aMap)
return nil
}
另一個解決方法是洗掉方法 CustomMap.UnmarshalJSON
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/516135.html
標籤:数组json去
