1 回答
TA贡献1820条经验 获得超2个赞
一种方法是实施自定义json.Unmarshaler
:
type Obj struct {
Status int
Message string
CoolKeys map[string]Person
}
type Person struct {
Name string
Age int
}
func (o *Obj) UnmarshalJSON(data []byte) error {
// first, unmarshal the object into a map of raw json
var m map[string]json.RawMessage
if err := json.Unmarshal(data, &m); err != nil {
return err
}
// next, unmarshal the status and message fields, and any
// other fields that don't belong to the "CoolKey" group
if err := json.Unmarshal(m["status"], &o.Status); err != nil {
return err
}
delete(m, "status") // make sure to delete it from the map
if err := json.Unmarshal(m["message"], &o.Message); err != nil {
return err
}
delete(m, "message") // make sure to delete it from the map
// finally, unmarshal the rest of the map's content
o.CoolKeys = make(map[string]Person)
for k, v := range m {
var p Person
if err := json.Unmarshal(v, &p); err != nil {
return err
}
o.CoolKeys[k] = p
}
return nil
}
https://go.dev/play/p/s4YCmve-pnz
- 1 回答
- 0 关注
- 99 浏览
添加回答
举报