所以我有一個結構: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 回答

翻翻過去那場雪
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
- 2 回答
- 0 關注
- 800 瀏覽
添加回答
舉報
0/150
提交
取消