亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

具有零/空值的指針上的客戶解組器/編組器

具有零/空值的指針上的客戶解組器/編組器

Go
達令說 2023-02-21 15:49:26
Golang - 具有零/空值的指針上的客戶解組器/編組器我正在嘗試實現自定義UnmarshalJSON和MarshalJSON指針類型,但是當來自 json 的數據null/nil如下例所示時,不會調用此函數: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指針類型的值調用我們如何UnmarshalJSON/MarshalJSON每次調用數據null/nil和類型是指針而不是UnmarshalJSON/MarshalJSON在A類型上實現并b從級別修改屬性A
查看完整描述

1 回答

?
夢里花落0921

TA貢獻1772條經驗 獲得超6個贊

簡稱

目前,解組/編組 Go 結構將僅發出非零字段,因為在 Go 中nil pointer是一個零值,在這種情況下不會調用。UnmarshalJSON/MarshalJSON


另外,似乎有一些相關的建議

但是,現在沒有辦法解決。


每個代碼 解組器

Unmarshalers 將 UnmarshalJSON([]byte("null")) 實現為空操作

// By convention, to approximate the behavior of Unmarshal itself,

// Unmarshalers implement UnmarshalJSON([]byte("null")) as a no-op.

type Unmarshaler interface {

    UnmarshalJSON([]byte) error

}


查看完整回答
反對 回復 2023-02-21
  • 1 回答
  • 0 關注
  • 123 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號