24
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Structをomitemptyする方法

Last updated at Posted at 2017-06-07

↓こんなStructがあったとして、JSONに変換した時にOrderItemプロパティが空だったら、JSONから省略したい。

HogeSales struct {
	IsDirty 	bool		`json:"-"`
	Id 			string      `json:"Id,omitempty"`
	Amount 		int		 	`json:"Amount,omitempty"`
	OrderItem	OrderItem	`json:"OrderItem,omitempty"`
}

json.Marshal(HogeSales) でJSONに変換した時に "OrderItem": {} となることを防ぐ方法。
このOrderItem項目すら消したい場合。

ちなみに omitempty される条件は下記

false, 0, any nil pointer or interface value, and any array, slice, map, or string of length zero

そう、Struct型である以上、Omitされない。。。

対処方法は簡単 Pointer にして nil を入れておけばOK

HogeSales struct {
	IsDirty 	bool		`json:"-"`
	Id 			string      `json:"Id,omitempty"`
	Amount 		int		 	`json:"Amount,omitempty"`
	OrderItem	*OrderItem	`json:"OrderItem,omitempty"`
}

func (h *HogeSales) Clear() {
	h.OrderItem = nil
}
24
18
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
24
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?