亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 golang 返回一個空數組而不是 null 用于使用 gin 返回的 json

使用 golang 返回一個空數組而不是 null 用于使用 gin 返回的 json

Go
海綿寶寶撒 2023-06-19 15:37:21
所以我有一個結構:type ProductConstructed struct {    Name string `json:"Name"`    BrandMedals []string `json:"BRAND_MEDALS"`}當我用杜松子酒返回我的對象時:func  contructproduct(c *gin.Context) {    var response ProductConstructed     response.Name = "toto"    c.JSON(200, response)}func main() {    var err error    if err != nil {        panic(err)    }    //gin.SetMode(gin.ReleaseMode)    r := gin.Default()    r.POST("/constructProductGo/v1/constructProduct", contructproduct)    r.Run(":8200") // listen and serve on 0.0.0.0:8080}它返回我:無效的代替[]如何返回空數組?問候
查看完整描述

2 回答

?
qq_花開花謝_0

TA貢獻1835條經驗 獲得超7個贊

所以解決方案是用以下方法初始化它:

productConstructed.BrandMedals = make([]string, 0)


查看完整回答
反對 回復 2023-06-19
?
翻翻過去那場雪

TA貢獻2065條經驗 獲得超14個贊

只是為了闡明上述解決方案為何有效:


slice1已聲明,但未定義。尚未為其分配任何變量,它等于nil. 序列化后,它將返回null.


slice2被聲明和定義。它等于一個空切片,而不是nil. 序列化后,它將返回[].


var slice1 []string? // nil slice value

slice2 := []string{} // non-nil but zero-length


json1, _ := json.Marshal(slice1)

json2, _ := json.Marshal(slice2)


fmt.Printf("%s\n", json1) // null

fmt.Printf("%s\n", json2) // []


fmt.Println(slice1 == nil) // true

fmt.Println(slice2 == nil) // false

去游樂場:https://play.golang.org/p/m9YEQYpJLdj

查看完整回答
反對 回復 2023-06-19
  • 2 回答
  • 0 關注
  • 800 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號