如果 JSON 中不存在该字段,Golang 的 json.Unmarshal 不会显式将指针值设置为 nil

如果 json 中不存在该字段,golang 的 json.unmarshal 不会显式将指针值设置为 nil

根据php小编子墨的介绍,Golang中的json.Unmarshal在解析JSON数据时,如果JSON中不存在某个字段,它不会将指针值显式设置为nil。这意味着即使JSON中缺少某个字段,指针仍然会保留其原始值,可能会导致程序出现错误或异常。因此,在使用json.Unmarshal时,我们需要特别注意处理缺失字段的情况,以确保程序的稳定性和正确性。

问题内容

考虑这个例子:

package mainimport (    "encoding/json"    "fmt")type InternalStructFirst struct {    Field string `json:"field"`}type ExternalStruct struct {    StructA InternalStructFirst `json:"struct_a"`    StructB *InternalStructFirst `json:"struct_b"`}func main() {    var structVar ExternalStruct    string1 := "{"struct_a":{"field":"a"},"struct_b":{"field":"b"}}"    json.Unmarshal([]byte(string1), &structVar)    fmt.Printf("first: %+v %+v", structVar.StructA, structVar.StructB)    string2 := "{"struct_a":{"field":"c"}}"    json.Unmarshal([]byte(string2), &structVar)    fmt.Printf("second: %+v %+v", structVar.StructA, structVar.StructB)    var structVar2 ExternalStruct    json.Unmarshal([]byte(string2), &structVar)    fmt.Printf("third: %+v %+v", structVar2.StructA, structVar2}

登录后复制

哪些输出:

first: {Field:a} &{Field:b}second: {Field:c} &{Field:b}third: {Field:} 

登录后复制

当我第一次执行 json.Unmarshal 时,StructB 出现在响应中,并且已正确解组。但是当我第二次执行此操作时,当响应中未显示该字段时,它似乎没有明确将其设置为 nil。当对没有设置此字段的结构执行此操作时,它确实将其设置为 nil (或者显然没有将其设置为某些内容)(如第三个示例所示)。

立即学习“go语言免费学习笔记(深入)”;

如果我已将 struct_b 设置为非 nil,如何更改我的示例,以便在解析其中不包含 struct_b 字段的 JSON 字符串时,第二个 json.Unmarshal 将显式将 StructB 设置为 nil ?

解决方法

你不能。 json.Unmarshal 不会修改输入 JSON 中未表示的结构字段。要么使用空结构开始,要么在调用 Unmarshal 之前将任何字段设置为您希望它们具有的任何值(如果它们不在 JSON 输入中)。

以上就是如果 JSON 中不存在该字段,Golang 的 json.Unmarshal 不会显式将指针值设置为 nil的详细内容,更多请关注【创想鸟】其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。

发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2358364.html

(0)
上一篇 2025年3月1日 16:58:26
下一篇 2025年3月1日 16:59:05

AD推荐 黄金广告位招租... 更多推荐

相关推荐

发表回复

登录后才能评论