duanbi7204 2016-08-04 14:42
浏览 2

空的响应结构

I have a query which casts into a struct. But when the query returns no results the response is null - how do I get this to be an empty array []?

_, err := dbmap.Select(&response.DevTeam, "SELECT * FROM DevTeam WHERE app_id = ? LIMIT ? OFFSET ?", a_id, limit, offset)

Response when no results:

{
  "data": null,
  "meta": "success"
}

Desired response when no results:

{
  "data": [],
  "meta": "success"
}

Still getting null - my struct setup is:

type HttpResonse struct {
    DevTeam []DevTeam `json:"data"`
}

I am using response.DevTeam = []models.DevTeam{} as suggested below but still getting null.

Response section:

s.Count = int64(len(response.DevTeam))  
c.JSON(httpcode, gin.H{"meta": s, "data": response.DevTeam})
  • 写回答

1条回答 默认 最新

  • doupu1727 2016-08-04 14:45
    关注

    A value of slice type being nil encodes as the null JSON object. A non-nil empty slice is marshaled into an empty array [].

    Before marshaling response, check the DevTeam field, and if it's nil, explicitly set a slice value with 0 length, e.g.:

    if response.DevTeam == nil {
       response.DevTeam = []models.DevTeam{} 
    }
    

    Or alternatively when you create your gin.H wrapper, use an empty slice instead of response.DevTeam if the latter equals to nil.

    See this simple example:

    type Pt struct {
        DevTeam []string
    }
    
    p := Pt{}
    json.NewEncoder(os.Stdout).Encode(p)
    
    p.DevTeam = []string{}
    json.NewEncoder(os.Stdout).Encode(p)
    

    Output (try it on the <kbd>Go Playground</kbd>):

    {"DevTeam":null}
    {"DevTeam":[]}
    
    评论

报告相同问题?

悬赏问题

  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题