当您对Go中的对象进行编码或解码时,未显式设置的类型将被填充为其默认值。字符串将默认为空字符串,整数将默认为0。通常这没什么问题,但当0在业务上包含其他含义时,歧义就出现了。

此外,如果使用结构标记,例如json omitempty,即使它们有效,也会忽略0值。 另一个例子是从SQL返回的Null。 对于Int来说,什么值最能代表Null?本文将探讨Go开发人员处理此问题的一些方法。

实践

1.建立 base.go:

package nulls

import (
    "encoding/json"
    "fmt"
)

const (
    jsonBlob     = `{"name": "Aaron"}`
    fulljsonBlob = `{"name":"Aaron", "age":0}`
)

// Example结构体包含age和name字段
type Example struct {
    Age  int    `json:"age,omitempty"`
    Name string `json:"name"`
}

// BaseEncoding 演示了基本的编码和解码操作
func BaseEncoding() error {
    e := Example{}

    // 注意jsonBlob没有age字段
    if err := json.Unmarshal([]byte(jsonBlob), &e); err != nil {
        return err
    }
    fmt.Printf("Regular Unmarshal, no age: %+v\n", e)

    value, err := json.Marshal(&e)
    if err != nil {
        return err
    }
    //由于age被设置为omitempty(为空则不输出) 所以显示 Regular Marshal, with no age: {"name":"Aaron"}
    fmt.Println("Regular Marshal, with no age:", string(value))

    if err := json.Unmarshal([]byte(fulljsonBlob), &e); err != nil {
        return err
    }
    fmt.Printf("Regular Unmarshal, with age = 0: %+v\n", e)

    value, err = json.Marshal(&e)
    if err != nil {
        return err
    }
    //Regular Marshal, with age = 0: {"name":"Aaron"}
    fmt.Println("Regular Marshal, with age = 0:", string(value))

    return nil
}

2.建立pointer.go:

package nulls

import (
    "encoding/json"
    "fmt"
)

// 和上一个例子类似 但是*int类型会出现奇妙的nil
// uses a *Int
type ExamplePointer struct {
    Age  *int   `json:"age,omitempty"`
    Name string `json:"name"`
}

func PointerEncoding() error {

    e := ExamplePointer{}
    if err := json.Unmarshal([]byte(jsonBlob), &e); err != nil {
        return err
    }
    //Pointer Unmarshal, no age: {Age:<nil> Name:Aaron}
    fmt.Printf("Pointer Unmarshal, no age: %+v\n", e)

    value, err := json.Marshal(&e)
    if err != nil {
        return err
    }
    //Pointer Marshal, with no age: {"name":"Aaron"}
    fmt.Println("Pointer Marshal, with no age:", string(value))

    if err := json.Unmarshal([]byte(fulljsonBlob), &e); err != nil {
        return err
    }
    //Pointer Unmarshal, with age = 0: {Age:0xc04200e4b8 Name:Aaron}
    fmt.Printf("Pointer Unmarshal, with age = 0: %+v\n", e)

    value, err = json.Marshal(&e)
    if err != nil {
        return err
    }
    //Pointer Marshal, with age = 0: {"age":0,"name":"Aaron"}
    fmt.Println("Pointer Marshal, with age = 0:", string(value))

    return nil
}

3.建立nullencoding.go:

package nulls

import (
    "database/sql"
    "encoding/json"
    "fmt"
)

type nullInt64 sql.NullInt64

// 和前面的例子类似 又改变了Age的类型sql.NullInt64
type ExampleNullInt struct {
    Age  *nullInt64 `json:"age,omitempty"`
    Name string     `json:"name"`
}

func (v *nullInt64) MarshalJSON() ([]byte, error) {
    if v.Valid {
        return json.Marshal(v.Int64)
    }
    return json.Marshal(nil)
}

func (v *nullInt64) UnmarshalJSON(b []byte) error {
    v.Valid = false
    if b != nil {
        v.Valid = true
        return json.Unmarshal(b, &v.Int64)
    }
    return nil
}

func NullEncoding() error {
    e := ExampleNullInt{}

    if err := json.Unmarshal([]byte(jsonBlob), &e); err != nil {
        return err
    }
    //nullInt64 Unmarshal, no age: {Age:<nil> Name:Aaron}
    fmt.Printf("nullInt64 Unmarshal, no age: %+v\n", e)

    value, err := json.Marshal(&e)
    if err != nil {
        return err
    }
    //nullInt64 Marshal, with no age: {"name":"Aaron"}
    fmt.Println("nullInt64 Marshal, with no age:", string(value))

    if err := json.Unmarshal([]byte(fulljsonBlob), &e); err != nil {
        return err
    }
    //nullInt64 Unmarshal, with age = 0: {Age:0xc0420623f0 Name:Aaron}
    fmt.Printf("nullInt64 Unmarshal, with age = 0: %+v\n", e)

    value, err = json.Marshal(&e)
    if err != nil {
        return err
    }
    //nullInt64 Marshal, with age = 0: {"age":0,"name":"Aaron"}
    fmt.Println("nullInt64 Marshal, with age = 0:", string(value))

    return nil
}

4.建立main.go:

package main

import (
    "fmt"

    "github.com/agtorre/go-cookbook/chapter3/nulls"
)

func main() {
    if err := nulls.BaseEncoding(); err != nil {
        panic(err)
    }
    fmt.Println()

    if err := nulls.PointerEncoding(); err != nil {
        panic(err)
    }
    fmt.Println()

    if err := nulls.NullEncoding(); err != nil {
        panic(err)
    }
}

5.这会输出:

Regular Unmarshal, no age: {Age:0 Name:Aaron}
Regular Marshal, with no age: {"name":"Aaron"}
Regular Unmarshal, with age = 0: {Age:0 Name:Aaron}
Regular Marshal, with age = 0: {"name":"Aaron"}
Pointer Unmarshal, no age: {Age:<nil> Name:Aaron}
Pointer Marshal, with no age: {"name":"Aaron"}
Pointer Unmarshal, with age = 0: {Age:0xc42000a610 Name:Aaron}
Pointer Marshal, with age = 0: {"age":0,"name":"Aaron"}
nullInt64 Unmarshal, no age: {Age:<nil> Name:Aaron}
nullInt64 Marshal, with no age: {"name":"Aaron"}
nullInt64 Unmarshal, with age = 0: {Age:0xc42000a750 Name:Aaron}
nullInt64 Marshal, with age = 0: {"age":0,"name":"Aaron"}

说明

从值切换到指针是表示空值的快速方法。这可能会为初始化带来点麻烦,因为无法直接操作*a := 1。除此之外这是一种不错的处理方式。

本节还演示了使用sql.NullInt64类型的替代方法。这通常与SQL一起使用,如果返回Null以外的任何内容,则设置valid,否则设置为Null。我们添加了MarshalJSON和UnmarshallJSON方法以允许此类型与JSON包交互,我们选择使用指针,以便omitempty将继续按预期工作。

最后编辑: kuteng  文档更新时间: 2021-01-03 15:03   作者:kuteng