相关疑难解决方法(0)

从struct中删除字段或将其隐藏在JSON Response中

我在Go中创建了一个API,在被调用时,执行查询,创建结构的实例,然后在发送回调用者之前将该结构编码为JSON.我现在想让调用者能够通过传入"fields"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
Run Code Online (Sandbox Code Playgroud)

然后我编码并输出响应,如下所示:

err := json.NewEncoder(c.ResponseWriter).Encode(&msg)
Run Code Online (Sandbox Code Playgroud)

json go

157
推荐指数
9
解决办法
11万
查看次数

标签 统计

go ×1

json ×1