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

type Goods struct {
    IDAutoModel
    CategoryIDModel // 商品分类
    NameModel
    DescriptionModel      // 商品特色描述
    Stores        uint64         `json:"stores"`             // 库存数
    MinScore      uint64         `json:"min_score"`          // 积分
    Weight        float64        `json:"weight"`             // 重量
    TimeAllModel
    Category GoodsCategory `json:"category,omitempty"`
}

在 返回 Goods json 列表的时候 不想输出 Category struct。 如何 删除 struct 里面的 struct

返回 json 公用 一个 struct 有的接口返回 不需要 Category 没有关联查,所以是空的 struct

有些地方是 需要输出 Category 的, 比如商品详情页, 商品列表页 就不需要输出 商品关联的 Category

omitempty- 根本不行

阅读 15.9k
4 个回答

你用了omitempty是没问题的,然后要注意:
Category GoodsCategory -> Category *GoodsCategory
因为你给他具体struct是会有默认值的,这样omitempty就不起作用了,改成指针,默认就会是个nil,此时omiempty起作用

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包

使用tag json:"-"
或者结构体字段首字母小写

GoodsCategory是一个关联的结构体,用omitempty不行,除非改成指针 *GoodsCategory 这样它就对指针的零值nil起作用。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏