doulianxing4015 2017-05-25 12:40
浏览 82
已采纳

如何在Golang中响应所有包含标记为temp的字段(包括字段)?

In my Webservice, I have a model:

// Comment struct
type Comment struct {
    Owner            UserObject      `json:"owner"`
    ID               int64           `json:"id"`
    Message          string          `json:"message"`
    Mentions         []MentionObject `json:"mentions,omitempty"`
    CreatedAt        int64           `json:"created_at,omitempty"`
    UpdatedAt        int64           `json:"updated_at,omitempty"`
    Status           int             `json:"status,omitempty"`
    CanEdit          bool            `json:"can_edit"`
    CanDelete        bool            `json:"can_delete"`
}


// UserObject struct
type UserObject struct {
    ID       int64  `json:"id"`
    Username string `json:"username"`
    FullName string `json:"full_name"`
    Avatar   string `json:"avatar"`
}

// MentionObject struct
type MentionObject struct {
    ID     int64 `json:"id"`
    Length int64 `json:"length"`
    Offset int64 `json:"offset"`
}

I have use gin gonic to routing

routes.GET("/user", func(c *gin.Context) {
        c.JSON(200, Comment{})
    })

I need return all fields of this struct, I know that It going to response a json:

{
  "owner": {
    "id": 0,
    "username": "",
    "full_name": "",
    "avatar": ""
  },
  "id": 0,
  "message": "",
  "can_report": false,
  "can_edit": false,
  "can_delete": false
}

I know that This is right, but I still want response all of field. How to do that?

  • 写回答

1条回答 默认 最新

  • dqh1992 2017-05-25 12:59
    关注

    If you don't want to drop the omitempty value from the tag because you need it for some other purpose, you can either, if you're on Go 1.8+, define a new type identical to the one you want to serialize but without the omitempty tag values and then simply convert a value from the old type to the new type.

    Here's an example of the 1.8+ "tag ignoring" type conversion

    You can also define a new type with only those fields that are omitted in the original and then embed the original in the new type like so.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行