golang json 解析:重写 unmarshaljson 后字段丢失问题
本文将探讨一个 go 语言 json 解析问题:在自定义结构体的 unmarshaljson 方法后,部分字段值无法被正确解析的问题。
问题描述如下:代码定义了两个结构体 idarr 和 a,idarr 用于接收前端字符串数组并将其转换为 uint64 类型的数组,idarr 匿名嵌套在 a 结构体中。在 main 函数中,通过 json.unmarshal 解析 json 字符串,idarr 中的 ids 字段能够正确解析,但 a 结构体中的 more 字段的值始终为空。
package main
import (
"encoding/json"
"fmt"
"strconv"
)
type idarr struct {
ids []uint64 `json:"ids"`
}
type a struct {
idarr
more string `json:"more"`
}
func (s *idarr) unmarshaljson(data []byte) error {
type temp idarr
t := struct {
ids []string `json:"ids"`
*temp
}{
temp: (*temp)(s),
}
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))
}
return nil
}
func main() {
d := `
{"ids":["1213334"], "more": "text"}
`
a := &a{}
json.unmarshal([]byte(d), &a)
fmt.printf("%+v", a)
}问题的根源在于 go 语言中结构体的匿名嵌套和方法继承机制。由于 idarr 匿名嵌套在 a 结构体中,idarr 的方法会被 a 继承。当调用 json.unmarshal 时,实际上调用的是 a 继承的 unmarshaljson 方法,而这个方法只处理了 idarr 结构体,忽略了 a 结构体中的 more 字段。
解决方法:
Easily find JSON paths within JSON objects using our intuitive Json Path Finder
30
立即学习“go语言免费学习笔记(深入)”;
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 A struct {
IdArr IdArr
More string `json:"more"`
}此时无需重写 unmarshaljson 方法,go 语言自带的 json 解析机制即可正确解析。
需要注意的是,原代码中 unmarshaljson 方法里定义的 temp 类型是多余的,可以移除。 选择哪种方法取决于具体的代码设计和需求。
以上就是Go语言JSON解析:自定义UnmarshalJSON后字段丢失,如何解决?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号