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

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

解組到自定義接口

解組到自定義接口

Go
LEATH 2023-04-24 15:54:26
通常的解組方法是這樣的:atmosphereMap := make(map[string]interface{})err := json.Unmarshal(bytes, &atmosphereMap)但是如何將json數據解組到自定義接口:type CustomInterface interface {    G() float64} atmosphereMap := make(map[string]CustomInterface)err := json.Unmarshal(bytes, &atmosphereMap)第二種方式給我一個錯誤:panic: json: cannot unmarshal object into Go value of type main.CustomInterface如何正確地做到這一點?
查看完整描述

1 回答

?
UYOU

TA貢獻1878條經驗 獲得超4個贊

要解組為一組類型,它們都實現一個公共接口,您可以json.Unmarshaler在父類型上實現接口,map[string]CustomInterface在您的情況下:

type CustomInterfaceMap map[string]CustomInterface


func (m CustomInterfaceMap) UnmarshalJSON(b []byte) error {

? ? data := make(map[string]json.RawMessage)

? ? if err := json.Unmarshal(b, &data); err != nil {

? ? ? ? return err

? ? }

? ? for k, v := range data {

? ? ? ? var dst CustomInterface

? ? ? ? // populate dst with an instance of the actual type you want to unmarshal into

? ? ? ? if _, err := strconv.Atoi(string(v)); err == nil {

? ? ? ? ? ? dst = &CustomImplementationInt{} // notice the dereference

? ? ? ? } else {

? ? ? ? ? ? dst = &CustomImplementationFloat{}

? ? ? ? }


? ? ? ? if err := json.Unmarshal(v, dst); err != nil {

? ? ? ? ? ? return err

? ? ? ? }

? ? ? ? m[k] = dst

? ? }

? ? return nil

}

確保您解組為CustomInterfaceMap,而不是map[string]CustomInterface,否則自定義UnmarshalJSON方法將不會被調用。

json.RawMessage是一種有用的類型,它只是一個原始編碼的 JSON 值,這意味著它是一個簡單的[]byteJSON 以未解析的形式存儲在其中。


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

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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