1 回答

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 值,這意味著它是一個簡單的[]byte
JSON 以未解析的形式存儲在其中。
- 1 回答
- 0 關注
- 139 瀏覽
添加回答
舉報