我想更改当前函数以返回空JSON列表,目前它返回nil。
这是我目前的代码:
func(s * Service)projectsGet(c * gin.Context){ var projects [] * models.Project
…
一个 nil 切片编码为 null JSON对象。这是记录在 json.Marshal() :
nil
null
json.Marshal()
数组和切片值编码为JSON数组,除了[]字节编码为base64编码的字符串,和 的 nil slice编码为空JSON值 强> 。
如果你想要一个非 null 空JSON数组,使用非 nil 空转片。
看这个例子:
type Project struct { Name string `json:"name"` } enc := json.NewEncoder(os.Stdout) var ps []*Project enc.Encode(ps) ps = []*Project{} enc.Encode(ps)
输出(试试吧 去游乐场 ):
null []
所以在你的情况下确保 projects 不是 nil , 例如:
projects
projects = ps if projects == nil { projects = []*models.Project{} }