重写 unmarshaljson 后取不到值的原因与解决办法
在 go 中,嵌套的结构体的接口会被外层结构体继承。故在代码中,对 idarr 结构体重写 unmarshaljson 方法后,a 结构体也继承了该方法。
问题在于重写的 unmarshaljson 方法只处理了 idarr 结构体,导致 more 字段无法解析。
解决办法有以下几种:
func (s *a) unmarshaljson(data []byte) error { t := struct { ids []string `json:"ids"` more string `json:"more"` }{} if err := json.unmarshal(data, &t); err != nil { return err } for _, id := range t.ids { uid, err := strconv.parseint(id, 10, 64) if err != nil { return err } s.ids = append(s.ids, uint64(uid)) } s.more = t.more return nil }
type B struct { Ids []uint64 } type A struct { B More string `json:"more"` }
以上就是Go 中重写 UnmarshalJSON 后取不到值的原因与解决办法是什么?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号