我在Go中创建了一个API,它在被调用时执行查询,创建一个结构的实例,然后在发送回调用者之前将该结构编码为JSON。现在,我想让调用者能够通过传递一个“field”GET参数来选择他们想要返回的特定字段。
这意味着根据字段值的不同,我的结构也会发生变化。有什么方法可以从结构中删除字段吗?或者至少将它们动态地隐藏在JSON响应中?(注意:有时我有空值,所以JSON omitEmpty标记在这里不起作用)如果这两个都不可能,有没有更好的处理方法的建议?
下面是我正在使用的结构的一个较小版本:
type SearchResult struct {
Date string `json:"date"`
IdCompany int `json:"idCompany"`
Company string `json:"company"`
IdIndustry interface{} `json:"idIndustry"`
Industry string `json:"industry"`
IdContinent interface{} `json:"idContinent"`
Continent string `json:"continent"`
IdCountry interface{} `json:"idCountry"`
Country string `json:"country"`
IdState interface{} `json:"idState"`
State string `json:"state"`
IdCity interface{} `json:"idCity"`
City string `json:"city"`
} //SearchResult
type SearchResults struct {
NumberResults int `json:"numberResults"`
Results []SearchResult `json:"results"`
} //type SearchResults
然后对响应进行编码并输出,如下所示:
err := json.NewEncoder(c.ResponseWriter).Encode(&msg)
https://stackoverflow.com/questions/17306358
复制相似问题