douxian3170 2018-11-11 08:41
浏览 16
已采纳

如何在元帅内部省略条件结构域

There is struct of MyStruct.

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

Following code convert it to json.

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

I need to "OptionField" be optional. Some time it should exist in json with one of values [0, 1, 2, 3, ]. and in the other time it should exclude from json.

My problem is: omitempty will exclude it when the value is zero, and the default value of int is zero. Is there any way to omit field in condition (ex: omit if value is -1). Or there is any way to do it.

  • 写回答

1条回答 默认 最新

  • dptn69182 2018-11-11 08:50
    关注

    You could use *int instead of int and set the pointer value to nil in order to omit this.

    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}
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100