返回空列表,而不是null [英] Return empty list instead of null

查看:99
本文介绍了返回空列表,而不是null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想更改当前函数以返回空的JSON列表,当前它返回nil.

I want to change my current function to return empty JSON list, currently it returns 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)
}

我希望它返回[],我该怎么做?

I want it to return [], how I can do it?

推荐答案

nil切片编码为null JSON对象.记录在 json.Marshal() :

A nil slice encodes to a null JSON object. This is documented at json.Marshal():

数组和切片值编码为JSON数组,除了[] byte编码为base64编码的字符串,而 nil slice编码为空JSON值.

如果您想要一个非null空的JSON数组,请使用一个非nil空的Go切片.

If you want a non-null empty JSON array, use a non-nil empty Go slice.

请参见以下示例:

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,例如:

So in your case make sure projects is not nil, for example:

projects = ps
if projects == nil {
    projects = []*models.Project{}
}

这篇关于返回空列表,而不是null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆