【发布时间】:2013-06-22 18:47:14
【问题描述】:
我在 Go 中创建了一个 API,它在被调用时执行查询,创建一个结构的实例,然后将该结构编码为 JSON,然后再发送回调用者。我现在想让调用者能够通过传入“字段”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)
【问题讨论】:
-
@Jacob,根据 PuerkitoBio 的更新答案,我认为您误读了这个问题。 (当前)接受的可能不是 your 问题的“正确答案”,而是此处提出的问题! (当前)投票最高的答案可能会回答您的问题,但完全不适用于这个问题!