gpt4 book ai didi

json - 在 Go 中,为什么 JSON null 有时不会传递给 UnmarshalJSON 进行解码?

转载 作者:数据小太阳 更新时间:2023-10-29 03:35:41 27 4
gpt4 key购买 nike

Go 提供了 encoding/json.Unmarshaler 接口(interface),因此类型可以控制它们从 JSON 解码的方式。在几乎所有情况下,编码后的 JSON 值都直接传递给 UnmarshalJSON 方法,但如果 Unmarshaler 是一个指针并且 JSON 值为 null。在这种情况下,指针设置为 nil 而根本不调用 UnmarshalJSON。这是一个例子:

package main

import (
"encoding/json"
"fmt"
)

type T string

func (v *T) UnmarshalJSON(b []byte) error {
if b[0] == 'n' {
*v = "null"
} else {
*v = "not null"
}
return nil
}

func main() {
var a struct {
T T
PT1 *T
PT2 *T
}
a.PT1 = nil // just to be explicit
a.PT2 = new(T)
err := json.Unmarshal([]byte(`{"T":null,"PT1":"foo","PT2":null}`), &a)
if err != nil {
panic(err)
}
fmt.Printf("a.T is %#v\n", a.T)
if a.PT1 == nil {
fmt.Println("a.PT1 is nil")
} else {
fmt.Printf("a.PT1 points to %#v\n", *a.PT1)
}
if a.PT2 == nil {
fmt.Println("a.PT2 is nil")
} else {
fmt.Printf("a.PT2 points to %#v\n", *a.PT2)
}
}

我希望它能打印出来

a.T is "null"
a.PT1 points to "not null"
a.PT2 points to "null"

相反,它打印

a.T is "null"
a.PT1 points to "not null"
a.PT2 is nil

所以json.Unmarshala.PT1分配了一个新的T,它最初是nil。但是它将 a.PT2 设置为 nil 而没有调用 UnmarshalJSON,即使 a.PT2 不是 。为什么?

最佳答案

这是因为将指针设置为 nil 是处理 JSON null 的最常见方式,而 UnmarshalJSON 则没有办法> *T 的方法自行完成。如果在这种情况下调用了 UnmarshalJSON,则必须定义 (**T).UnmarshalJSON 以将 *T 设置为 。这会使最常见的情况变得非常尴尬。

如果你不想让 JSON null 变成 Go nil,就不要使用指针。

关于json - 在 Go 中,为什么 JSON null 有时不会传递给 UnmarshalJSON 进行解码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34163625/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com