Go语言嵌套JSON反序列化自定义结构体字段为空,如何优雅处理?
问题根因分析
最核心错误:反序列化类型不匹配
你提供的MongoDB返回结果是JSON数组,但是你直接尝试反序列化到单个Customer结构体,json.Unmarshal会直接报错终止执行,你没有处理返回的error,导致所有字段都保留初始化零值,这就是你看到Address、Name、Email全部为空的直接原因。ID字段为空的结构匹配问题
你给内嵌的Document结构体加了json:"document"标签,意味着Document的所有字段都会映射到JSON的document子对象下,但你的JSON中_id字段在根层级,document子对象内只有createdat和updatedat,自然找不到对应值给Document.ID赋值。
干净的解决方案,无需自定义Unmarshal
完全不需要重写Unmarshal方法,两步修改即可:
第一步:修正反序列化类型,增加错误检查
将反序列化目标改为[]Customer切片,处理完再取需要的元素:
var customerList []Entities.Customer // 一定要检查error!90%的序列化问题都能通过error定位 err := json.Unmarshal(customerEntityBytes, &customerList) if err != nil { // 按需处理错误 panic(err) } if len(customerList) == 0 { // 处理无数据的情况 return } customerEntity := customerList[0]
第二步:调整Customer结构体适配JSON层级
在Customer外层新增ID字段覆盖内嵌Document的ID,匹配根层级的_id即可,不需要修改原有Document、Address的定义:
type Customer struct { ID string `json:"_id,omitempty"` // 新增,对应根级_id Document `json:"document"` Address Address `json:"address"` Name string `json:"name,omitempty"` Email string `json:"email,omitempty"` Valid bool `json:"valid,omitempty"` }
Go语言中结构体外层字段优先级高于内嵌结构体的同名字段,该写法完全兼容你原有的公共属性抽象,后续Document修改其他字段也不需要调整这部分代码。
内容的提问来源于stack exchange,提问作者NeedMoreCoffee
相关产品推荐
相关产品推荐

