【问题标题】:How to omit conditional field of struct within marshal如何在元帅中省略结构的条件字段
【发布时间】:2018-11-11 08:41:25
【问题描述】:

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在值为0的时候会排除,而int的默认值是0。有没有办法在条件中省略字段(例如:如果值为-1,则省略)。或者有什么办法。

【问题讨论】:

标签: go


【解决方案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}
}

【讨论】:

    猜你喜欢
    • 2020-12-12
    • 2022-10-13
    • 2022-10-18
    • 1970-01-01
    • 1970-01-01
    • 2019-12-20
    • 1970-01-01
    • 2021-10-24
    • 2019-12-12
    相关资源
    最近更新 更多