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

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?

  • 写回答

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条)

报告相同问题?

悬赏问题

  • ¥15 vhdl+MODELSIM
  • ¥20 simulink中怎么使用solve函数?
  • ¥30 dspbuilder中使用signalcompiler时报错Error during compilation: Fitter failed,求解决办法
  • ¥15 gwas 分析-数据质控之过滤稀有突变中出现的问题
  • ¥15 没有注册类 (异常来自 HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))
  • ¥15 知识蒸馏实战博客问题
  • ¥15 用PLC设计纸袋糊底机送料系统
  • ¥15 simulink仿真中dtc控制永磁同步电机如何控制开关频率
  • ¥15 用C语言输入方程怎么
  • ¥15 网站显示不安全连接问题