首頁 > 後端開發 > Golang > 主體

如果 JSON 中不存在該字段,Golang 的 json.Unmarshal 不會明確將指標值設為 nil

WBOY
發布: 2024-02-09 08:12:08
轉載
807 人瀏覽過

如果 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 字串時,第二個json.Unmarshal 將明確將StructB 設為nil ?

解決方法

你不能。 json.Unmarshal 不會修改輸入 JSON 中未表示的結構欄位。要么使用空結構開始,要么在調用 Unmarshal 之前將任何字段設置為您希望它們具有的任何值(如果它們不在 JSON 輸入中)。

以上是如果 JSON 中不存在該字段,Golang 的 json.Unmarshal 不會明確將指標值設為 nil的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:stackoverflow.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!