go - 如何在编码(marshal)中省略结构的条件字段

标签 go

MyStruct结构体

type MyStruct struct {
    Code        int   `json:"Code"`
    Flags       uint8 `json:"Flags"`
    OptionField int   `json:",omitempty"`
}

以下代码将其转换为 json。

f := MyStruct{Code:500, OptionField:41}
r, _ := json.Marshal(f)
fmt.Println(string(r)

我需要“OptionField”是可选的。有时它应该存在于 json 中,其值为 [0, 1, 2, 3, ] 之一。在其他时间它应该从 json 中排除。

我的问题是:omitempty 会在值为零时将其排除,而 int 的默认值为零。有什么方法可以省略条件中的字段(例如:如果值为 -1 则省略)。或者有什么办法可以做到。

最佳答案

您可以使用 *int 而不是 int 并将指针值设置为 nil 以省略它。

package main

import (
    "encoding/json"
    "fmt"
)

type MyStruct struct {
    Code        int   `json:"Code"`
    Flags       uint8 `json:"Flags"`
    OptionField *int  `json:",omitempty"`
}

func format(s MyStruct) string {
    r, _ := json.Marshal(s)
    return string(r)
}

func main() {
    f := MyStruct{Code: 500, Flags: 10, OptionField: new(int)}
    fmt.Println(format(f)) // {"Code":500,"Flags":10,"OptionField":0}
    f.OptionField = nil
    fmt.Println(format(f)) // {"Code":500,"Flags":10}
}

关于go - 如何在编码(marshal)中省略结构的条件字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53247098/

相关文章:

Gorm 不创建条目

go - 将 yaml 文件注入(inject) Argo 工作流程步骤的最佳方法是什么?

去如何检查一个函数是否存在

go - 在 GO 中将字符串转换为函数名称?

Golang 不能使用类型作为参数中的类型

unit-testing - 如何从子目录访问测试方法

algorithm - 如何对 trie 表中的 IP 地址进行排序?

import - 去+ revel : How to import custom package?

go - 字符串到二维 slice

google-app-engine - 如何使 vendor 与 Google App Engine 一起工作?