具有零/空值的指针上的客户解组器/编组器

Golang - 具有零/空值的指针上的客户解组器/编组器

我正在尝试实现自定义UnmarshalJSON和MarshalJSON指针类型,但是当来自 json 的数据null/nil如下例所示时,不会调用此函数:


package main


import (

    "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 value

func (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` value

func (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 called

a: {B:3}

MarshalJSON on B called

b: {"b":7}

我的问题是:

  • 为什么UnmarshalJSON/MarshalJSON不使用null/nil指针类型的值调用

  • 我们如何UnmarshalJSON/MarshalJSON每次调用数据null/nil和类型是指针而不是UnmarshalJSON/MarshalJSONA类型上实现并b从级别修改属性A


达令说
浏览 104回答 1
1回答

梦里花落0921

简称目前,解组/编组 Go 结构将仅发出非零字段,因为在 Go 中nil pointer是一个零值,在这种情况下不会调用。UnmarshalJSON/MarshalJSON另外,似乎有一些相关的建议提案:编码/json:添加 omitzero 选项提案:encoding/json:允许从 MarshalJSON 返回 nil 以省略该字段但是,现在没有办法解决。每个代码 解组器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}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go