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?
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.