簡體   English   中英

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

[英]Return an empty array instead of null with golang for json return with gin

所以我有一個結構:

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
}

它返回我:

空值

代替

[]

如何返回一個空數組?

問候

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

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

只是為了澄清為什么上述解決方案有效:

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

更多信息: https : //github.com/golang/go/wiki/CodeReviewComments#declaring-empty-slices

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM