在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/Java  GO  網(wǎng)絡(luò)安全/ golang json 返回 不需要輸出的 struct 字段

golang json 返回 不需要輸出的 struct 字段

type Goods struct {
    IDAutoModel
    CategoryIDModel // 商品分類
    NameModel
    DescriptionModel      // 商品特色描述
    Stores        uint64         `json:"stores"`             // 庫存數(shù)
    MinScore      uint64         `json:"min_score"`          // 積分
    Weight        float64        `json:"weight"`             // 重量
    TimeAllModel
    Category GoodsCategory `json:"category,omitempty"`
}

在 返回 Goods json 列表的時(shí)候 不想輸出 Category struct。 如何 刪除 struct 里面的 struct

返回 json 公用 一個(gè) struct 有的接口返回 不需要 Category 沒有關(guān)聯(lián)查,所以是空的 struct

有些地方是 需要輸出 Category 的, 比如商品詳情頁, 商品列表頁 就不需要輸出 商品關(guān)聯(lián)的 Category

omitempty- 根本不行

回答
編輯回答
九年囚

Struct values encode as JSON objects. Each exported struct field becomes a member of the object unless

  • the field's tag is "-", or
  • the field is empty and its tag specifies the "omitempty" option.

The empty values are false, 0, any nil pointer or interface value, and any array, slice, map, or string of length zero. The object's default key string is the struct field name but can be specified in the struct field's tag value. The "json" key in the struct field's tag value is the key name, followed by an optional comma and options. Examples:

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

// 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"
The "string" option signals that a field is stored as JSON inside a JSON-encoded string. It applies only to fields of string, floating point, integer, or boolean types. This extra level of encoding is sometimes used when communicating with JavaScript programs:

Int64String int64 json:",string"
The key name will be used if it's a non-empty string consisting of only Unicode letters, digits, dollar signs, percent signs, hyphens, underscores and slashes.

GO官方Json包

2018年9月1日 13:25
編輯回答
雨蝶

你用了omitempty是沒問題的,然后要注意:
Category GoodsCategory -> Category *GoodsCategory
因?yàn)槟憬o他具體struct是會(huì)有默認(rèn)值的,這樣omitempty就不起作用了,改成指針,默認(rèn)就會(huì)是個(gè)nil,此時(shí)omiempty起作用

2017年5月30日 18:00
編輯回答
遲月

使用tag json:"-"
或者結(jié)構(gòu)體字段首字母小寫

2018年8月12日 22:57