我有一个用户结构:
type User struct {
gorm.Model
Email string
Password string
AccountType int
CompanyId int
FirstName string
LastName string
PhoneNumber string
RecoveryEmail string
Contractor bool `gorm:"sql:'not null' default:'false'"`
}
我正在使用此结构通过gorm
从数据库中获取一行:
// Get a specific user from the database.
func getUser(id uint) (*User, error) {
var user User
if err := database.Connection.Select("id, created_at, email, account_type, company_id, first_name, last_name").Where("id = ? ", id).First(&user).Error; err != nil {
return nil, err
}
fmt.Println(&user)
return &user, nil
}
我的杜松子酒:
// @Summary Attempts to get a existing user by id
// @tags users
// @Router /api/users/getUserById [get]
func HandleGetUserById(c *gin.Context) {
// Were using delete params as it shares the same interface.
var json deleteParams
if err := c.Bind(&json); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"message": "No user ID found, please try again."})
return
}
outcome, err := getUser(json.Id)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"message": "Something went wrong while trying to process that, please try again.", "error": err.Error()})
log.Println(err)
return
}
c.JSON(http.StatusOK, gin.H{
"message": "Successfully found user",
"user": outcome,
})
}
它可以很好地返回所有内容,但是当我返回&user
时,未选择的字段将使用默认值返回:
{
"message": "Successfully found user",
"user": {
"ID": 53,
"CreatedAt": "2018-06-24T00:05:49.761736+01:00",
"UpdatedAt": "0001-01-01T00:00:00Z",
"DeletedAt": null,
"Email": "jack@jackner.com",
"Password": "",
"AccountType": 0,
"CompanyId": 2,
"FirstName": "",
"LastName": "",
"PhoneNumber": "",
"RecoveryEmail": "",
"Contractor": false
}
}
是否有办法从对象中删除空或空属性?还是我必须发回一个对象,并将其值映射到所述新对象?如果有一种简单的方法可以使用辅助函数来完成前者,那么我想知道如何做。
答案 0 :(得分:5)
您可以在对象的字段定义中指定omitempty
标签。
示例:
Email string `json:",omitempty"`
如果以这种方式定义字段,则JSON输出中将不会出现空值:
https://golang.org/pkg/encoding/json/#Marshal
“ omitempty”选项指定,如果字段具有空值(定义为false,0,nil指针,nil接口值以及任何空数组,slice,map,或字符串。