首页  >  文章  >  后端开发  >  如果 JSON 中不存在该字段,Golang 的 json.Unmarshal 不会显式将指针值设置为 nil

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

WBOY
WBOY转载
2024-02-09 08:12:08791浏览

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

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

问题内容

考虑这个例子:

<code>package main

import (
    "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\n", structVar.StructA, structVar.StructB)

    string2 := "{\"struct_a\":{\"field\":\"c\"}}"
    json.Unmarshal([]byte(string2), &structVar)
    fmt.Printf("second: %+v %+v\n", structVar.StructA, structVar.StructB)

    var structVar2 ExternalStruct
    json.Unmarshal([]byte(string2), &structVar)
    fmt.Printf("third: %+v %+v\n", structVar2.StructA, structVar2
}


</code>

哪些输出:

first: {Field:a} &{Field:b}
second: {Field:c} &{Field:b}
third: {Field:} <nil>

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

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

解决方法

你不能。 json.Unmarshal 不会修改输入 JSON 中未表示的结构字段。要么使用空结构开始,要么在调用 Unmarshal 将显式将 StructB 设置为 nil ?

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

以上是如果 JSON 中不存在该字段,Golang 的 json.Unmarshal 不会显式将指针值设置为 nil的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:stackoverflow.com。如有侵权,请联系admin@php.cn删除