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.

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

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用