是否有一种方法可以强制对struct 中的所有字段强制,而不对每个字段显式指定?
type Item struct {
Name string `json:"item,omitempty"`
Quantity int `json:"quantity,omitempty"`
Price int `json:"price,omitempty"`
}这只是一个例子,原来的结构可能有太多的很多字段。
如果所有字段都需要omitempty,那么针对每个字段指定它既丑陋又多余。如果json.Marshal()有办法在封送时忽略空字段,那就太好了。有人能提出最好的方法来实现这一点吗?或者这是最好的方法?
发布于 2020-01-12 15:08:05
您可以实现json.Marshaller接口来进行自定义JSON编组。
示例:
// Your struct
type Item struct {
Name string `json:"item"`
Quantity int `json:"quantity"`
Price int `json:"price"`
}
func (i Item) MarshalJSON() ([]byte, error) {
return json.Marshal(&struct {
Name string `json:"name"` // Fields that you need
}{
Name: i.Name,
})
}然后:
i := Item{Name: "Apple", Price: 1200}
itemJSON, err := json.Marshal(i)
if err != nil {
log.Fatalf("%v", err)
}
fmt.Println(string(itemJSON)) // -> {"name":"Apple"}此外,您可能会发现这篇关于自定义编组的文章很有用。
另外,如果您需要不同的JSON表示,那么您的结构这篇文章将非常有用
https://stackoverflow.com/questions/59680212
复制相似问题