Golang - 具有零/空值的指針上的客戶解組器/編組器我正在嘗試實現(xiàn)自定義UnmarshalJSON和MarshalJSON指針類型,但是當(dāng)來自 json 的數(shù)據(jù)null/nil如下例所示時,不會調(diào)用此函數(shù):package mainimport ( "encoding/json" "fmt")type A struct { B *B `json:"b,omitempty"`}type B int// Only for displaying value instead of// pointer address when calling `fmt.Println`func (b *B) String() string { if b == nil { return "nil" } return fmt.Sprintf("%d", *b)}// This function is not triggered when json// data contains null instead of number valuefunc (b *B) UnmarshalJSON(data []byte) error { fmt.Println("UnmarshalJSON on B called") var value int if err := json.Unmarshal(data, &value); err != nil { return err } if value == 7 { *b = B(3) } return nil}// This function is not triggered when `B`// is pointer type and has `nil` valuefunc (b *B) MarshalJSON() ([]byte, error) { fmt.Println("MarshalJSON on B called") if b == nil { return json.Marshal(0) } if *b == 3 { return json.Marshal(7) } return json.Marshal(*b)}func main() { var a A // this won't call `UnmarshalJSON` json.Unmarshal([]byte(`{ "b": null }`), &a) fmt.Printf("a: %+v\n", a) // this won't call `MarshalJSON` b, _ := json.Marshal(a) fmt.Printf("b: %s\n\n", string(b)) // this would call `UnmarshalJSON` json.Unmarshal([]byte(`{ "b": 7 }`), &a) fmt.Printf("a: %+v\n", a) // this would call `MarshalJSON` b, _ = json.Marshal(a) fmt.Printf("b: %s\n\n", string(b))}輸出:a: {B:nil}b: {}UnmarshalJSON on B calleda: {B:3}MarshalJSON on B calledb: {"b":7}我的問題是:為什么UnmarshalJSON/MarshalJSON不使用null/nil指針類型的值調(diào)用我們?nèi)绾蜺nmarshalJSON/MarshalJSON每次調(diào)用數(shù)據(jù)null/nil和類型是指針而不是UnmarshalJSON/MarshalJSON在A類型上實現(xiàn)并b從級別修改屬性A
1 回答

夢里花落0921
TA貢獻1772條經(jīng)驗 獲得超6個贊
簡稱
目前,解組/編組 Go 結(jié)構(gòu)將僅發(fā)出非零字段,因為在 Go 中nil pointer
是一個零值,在這種情況下不會調(diào)用。UnmarshalJSON/MarshalJSON
另外,似乎有一些相關(guān)的建議
但是,現(xiàn)在沒有辦法解決。
每個代碼 解組器
Unmarshalers 將 UnmarshalJSON([]byte("null")) 實現(xiàn)為空操作
// By convention, to approximate the behavior of Unmarshal itself,
// Unmarshalers implement UnmarshalJSON([]byte("null")) as a no-op.
type Unmarshaler interface {
UnmarshalJSON([]byte) error
}
- 1 回答
- 0 關(guān)注
- 121 瀏覽
添加回答
舉報
0/150
提交
取消