go - 在 Go 中,定义明确的类型的 JSON 编码(marshal)处理会失败吗?

标签 go error-handling

给定以下代码:

package main

import (
    "encoding/json"
    "fmt"
    "log"
)

type Employee struct {
    Id int "json:id"
}

func main() {
    b, err := json.Marshal(&Employee{Id: 2})
    if err != nil {
        log.Fatal("Couldn't marshal the Employee")
    }

    fmt.Println(string(b))
}

使用 _ 占位符是否可以可靠地忽略检查错误,因为 Employee 结构已明确定义。理论上它应该永远不会失败,所以问题是忽略这种类型的错误并在这种类型的样板错误检查上节省一点点是一种好习惯吗?

忽略看起来像这样:

package main

import (
    "encoding/json"
    "fmt"
)

type Employee struct {
    Id int "json:id"
}

func main() {
    b, _ := json.Marshal(&Employee{Id: 2})
    fmt.Println(string(b))
}

最佳答案

Error handling and Go :

Proper error handling is an essential requirement of good software.


通常您的代码不会失败。但如果用户将此 MarshalJSON 方法接收器添加到您的类型,则会失败:

func (t *Employee) MarshalJSON() ([]byte, error) {
    if t.Id == 2 {
        return nil, fmt.Errorf("Forbiden Id = %d", t.Id)
    }
    data := []byte(fmt.Sprintf(`{"Id":%d}`, t.Id))
    return data, nil
}

此代码编译,但仅针对 Id == 2 (The Go Playground) 故意失败:

package main

import (
    "encoding/json"
    "fmt"
    "log"
)

type Employee struct {
    Id int "json:id"
}

func main() {
    b, err := json.Marshal(&Employee{Id: 2})
    if err != nil {
        log.Fatal("Couldn't marshal the Employee", err)
    }

    fmt.Println(string(b))
}

func (t *Employee) MarshalJSON() ([]byte, error) {
    if t.Id == 2 {
        return nil, fmt.Errorf("Forbiden Id = %d", t.Id)
    }
    data := []byte(fmt.Sprintf(`{"Id":%d}`, t.Id))
    return data, nil
}

此代码也可以编译,但失败(The Go Playground):

package main

import (
    "encoding/json"
    "fmt"
    "log"
)

type Employee struct {
    Id int "json:id"
}

func main() {
    b, err := json.Marshal(&Employee{Id: 2})
    if err != nil {
        log.Fatal("Couldn't marshal the Employee")
    }

    fmt.Println(string(b))
}

func (t Employee) MarshalJSON() ([]byte, error) {
    data := []byte(fmt.Sprint(t))
    return data, nil
}

关于go - 在 Go 中,定义明确的类型的 JSON 编码(marshal)处理会失败吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39109003/

相关文章:

Golang AES-CBC 256 使用 CryptoJS 解密

go - 为什么 LiteIDE 不构建选中/高亮的 go 文件?

firebase - 如何通过RPC监听Firestore

c++ - 输入布局,访问冲突,错误处理无法正常运行

angular - 处理http删除

reflection - reflect.Value 的字符串方法无法按预期工作

go - 编码(marshal)嵌入式结构

java - Android - 以编程方式添加按钮,设置 ID 崩溃

c++ - 我正在尝试制作一个循环来检查输入是否为数字,如果不是则再次询问

python - 关于幅度的语法错误