我在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)
发布于 2014-03-28 07:46:32
使用json:"-"
// Field is ignored by this package.
Field int `json:"-"`
// Field appears in JSON as key "myName".
Field int `json:"myName"`
// Field appears in JSON as key "myName" and
// the field is omitted from the object if its value is empty,
// as defined above.
Field int `json:"myName,omitempty"`
// Field appears in JSON as key "Field" (the default), but
// the field is skipped if empty.
// Note the leading comma.
Field int `json:",omitempty"`
发布于 2017-01-26 18:53:09
我刚刚发布了sheriff,它根据结构字段上注释的标记将结构转换为映射。然后,您可以编组(JSON或其他)生成的映射。它可能不允许您只序列化调用者请求的字段集,但我想使用一组组将允许您涵盖大多数情况。使用组而不是直接使用字段也很可能会增加缓存能力。
示例:
package main
import (
"encoding/json"
"fmt"
"log"
"github.com/hashicorp/go-version"
"github.com/liip/sheriff"
)
type User struct {
Username string `json:"username" groups:"api"`
Email string `json:"email" groups:"personal"`
Name string `json:"name" groups:"api"`
Roles []string `json:"roles" groups:"api" since:"2"`
}
func main() {
user := User{
Username: "alice",
Email: "alice@example.org",
Name: "Alice",
Roles: []string{"user", "admin"},
}
v2, err := version.NewVersion("2.0.0")
if err != nil {
log.Panic(err)
}
o := &sheriff.Options{
Groups: []string{"api"},
ApiVersion: v2,
}
data, err := sheriff.Marshal(o, user)
if err != nil {
log.Panic(err)
}
output, err := json.MarshalIndent(data, "", " ")
if err != nil {
log.Panic(err)
}
fmt.Printf("%s", output)
}
发布于 2013-06-26 07:46:16
你可以使用标签属性"omitifempty“,或者将可选字段设为指针,而不初始化那些你想跳过的字段。
https://stackoverflow.com/questions/17306358
复制相似问题