我想更改当前函数以返回空 JSON 列表,当前它返回nil
.
这是我当前的代码:
func (s *Service) projectsGet(c *gin.Context) {
var projects []*models.Project
user := getUser(c)
pag := models.NewPagination(c)
ps, err := s.db.ProjectsGet(user.ID, &pag)
if err != nil {
apiError(c, http.StatusInternalServerError, err)
return
}
projects = ps
c.JSON(http.StatusOK, projects)
}
我想让它回来[]
,我该怎么办呢?
A nil
切片编码为null
JSON 对象。这记录在json.Marshal() https://golang.org/pkg/encoding/json/#Marshal:
数组和切片值编码为 JSON 数组,但 []byte 编码为 base64 编码的字符串,并且nil 切片编码为 null JSON 值.
如果你想要一个非null
空 JSON 数组,使用非nil
空的 Go 切片。
看这个例子:
type Project struct {
Name string `json:"name"`
}
enc := json.NewEncoder(os.Stdout)
var ps []*Project
enc.Encode(ps)
ps = []*Project{}
enc.Encode(ps)
输出(尝试一下去游乐场 https://play.golang.org/p/4j26-eNEujb):
null
[]
所以在你的情况下请确保projects
is not nil
, 例如:
projects = ps
if projects == nil {
projects = []*models.Project{}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)