Json &引用;省略“空”;所有领域

Json &引用;省略“空”;所有领域,json,go,marshalling,Json,Go,Marshalling,是否有一种方法可以强制忽略结构中所有字段的空,而无需对每个字段显式指定它 type Item struct { Name string `json:"item,omitempty"` Quantity int `json:"quantity,omitempty"` Price int `json:"price,omitempty"` } 这只是一个例子,原始结构可能有太多的字段 如果我需要为所有字段指定ommitempty,那么针对每个字段指定

是否有一种方法可以强制
忽略结构中所有字段的空
,而无需对每个字段显式指定它

type Item struct {
    Name     string `json:"item,omitempty"`
    Quantity int    `json:"quantity,omitempty"`
    Price    int    `json:"price,omitempty"`
}
这只是一个例子,原始结构可能有太多的字段

如果我需要为所有字段指定
ommitempty
,那么针对每个字段指定
ommitempty
似乎既丑陋又多余。如果
json.marshall()
在进行封送处理时能够忽略空字段,那也太好了。有人能建议实现这一点的最佳方法吗?或者这是最好的方法?

您可以实现该接口来进行自定义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,
    })
}
然后:

此外,您可能会发现它很有用


此外,如果您需要结构的不同JSON表示形式,则非常有用

最好的方法是为所有字段指定
,省略空的
JSON.Marshal
接受一个参数:要封送的对象。无法指定该对象之外的任何配置,您可以使用标记指定配置,正如您所发现的那样。
i := Item{Name: "Apple", Price: 1200}
itemJSON, err := json.Marshal(i)
if err != nil {
    log.Fatalf("%v", err)
}

fmt.Println(string(itemJSON)) // -> {"name":"Apple"}