Go结构中omitempty的用例是什么?

时间:2018-03-01 05:52:56

标签: oop go struct

我很好奇用例如何用以下内容省略空:

type Example struct {
    ID           string  `json:",omitempty"`
    Name         string  `json:"name,omitempty"`
    exchangeRate float64 `json:"string"`
}

我已经读过omitempty阻止在打印结构时显示空值,但我对此并不乐观。 另外,为什么要包括结构值的名称,即Nameomitempty

1 个答案:

答案 0 :(得分:0)

感谢Cerise Limon建议在godoc.org上查看godocs。

根据编组JSON的部分:

  

Struct值编码为JSON对象。每个导出的struct字段   使用字段名称作为对象成为对象的成员   键,除非省略该字段。

     

每个字符串的字段可以通过存储的格式字符串进行自定义   在struct field的标签下的json键下。格式字符串给出   字段的名称,可能后跟逗号分隔的列表   选项。

     

" omitempty" option指定应省略该字段   如果字段具有空值,则编码,定义为false,0,a   nil指针,一个nil接口值,以及任何空数组,切片,map,   或字符串。

// Field appears in JSON as key "myName".
Field int `json:"myName"`

// Field appears in JSON as key "myName" and
// the field is omitted from the object if its value is empty,
// as defined above.
Field int `json:"myName,omitempty"`

// Field appears in JSON as key "Field" (the default), but
// the field is skipped if empty.
// Note the leading comma.
Field int `json:",omitempty"`

// Field is ignored by this package.
Field int `json:"-"`

// Field appears in JSON as key "-".
Field int `json:"-,"`
相关问题