卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章64334本站已运行4115

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

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

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

问题内容

考虑这个例子:

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 %+vn", structVar.StructA, structVar.StructB)

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

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


哪些输出:

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

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

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

解决方法

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

卓越飞翔博客
上一篇: hmac.New(h func() hash.Hash, key byte) hash.Hash 在 JavaScript 中等效
下一篇: 如何使 Protobuf 3 字段成为必填字段?
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏