duancui19840401
2014-07-16 00:19
浏览 351
已采纳

Golang中具有多个json表示的一个结构

The problem I'm trying to solve is that I have a Model of a community that looks like this

type Community struct {
    Name string
    Description string
    Sources []Source
    Popularity int
    FavoriteCount int
    Moderators []string
    Children []Community
    Tracks []Track
}

Communities hold a lot of information and there are scenarios when I want to return only part of the description such as if I'm returning a list of trending communities. In this case I'd want to return only

type Community struct {
    Name string
    Description string
    Popularity int
    FavoriteCount int
}

The only way I can think of doing this is to create a new type containing only those fields and write a convenience method that takes a community and returns that type, but essentially creating a new object and copying those fields by value, is there a better way to do this?

I'm aware of the json:"-" syntax, but I'm not sure of how you could do this on a case by case basis as I still need to sometimes return the full object, perhaps a different type that is typecasted to?

图片转代码服务由CSDN问答提供 功能建议

我要解决的问题是,我有一个像这样的社区模型

  type社区结构{
名称字符串
描述字符串
源[]源
流行度int 
 FavoriteCount int 
主持人[]字符串
儿童[]社区\  n跟踪[] Track 
} 
   
 
 

社区拥有很多信息,在某些情况下,我只想返回部分说明,例如 m返回趋势社区列表。 在这种情况下,我只想返回

  type社区结构{
名称字符串
描述字符串
流行度int 
 FavoriteCount int 
} 
 <  / code>  
 
 

我能想到的唯一方法是创建一个仅包含这些字段的新类型,并编写一个使用社区并返回该类型的便捷方法,但实际上是 一个新对象并按值复制这些字段,是否有更好的方法呢?

我知道 json:“-” 语法,但是我不确定如何根据具体情况进行操作 有时候我仍然需要返回完整的对象,也许是类型转换为其他类型的对象?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

4条回答 默认 最新

  • dongluo8439 2017-08-09 19:30
    最佳回答

    I developed a library which can help you in this regard: Sheriff

    You can annotate your struct fields with special tags and call Sheriff to transform the given struct into a subset of it. After that you can call json.Marshal() or whatever else you want to marshal into.

    Your example would become as simple as:

    type Community struct {
        Name          string      `json:"name" groups:"trending,detail"`
        Description   string      `json:"description" groups:"trending,detail"`
        Sources       []Source    `json:"sources" groups:"detail"`
        Popularity    int         `json:"popularity" groups:"trending,detail"`
        FavoriteCount int         `json:"favorite_count" groups:"trending,detail"`
        Moderators    []string    `json:"moderators" groups:"detail"`
        Children      []Community `json:"children" groups:"detail"`
        Tracks        []Track     `json:"tracks" groups:"detail"`
    }
    
    communities := []Community{
        // communities
    }
    
    o := sheriff.Options{
        Groups: []string{"trending"},
    }
    
    d, err := sheriff.Marshal(&o, communities)
    if err != nil {
        panic(err)
    }
    
    out, _ := json.Marshal(d)
    
    评论
    解决 无用
    打赏 举报
查看更多回答(3条)

相关推荐 更多相似问题