返回一个空阵列而不是与golang一起返回带有杜松子酒的JSON返回



所以我有一个结构:

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
}

它返回我:

null

而不是

[]

如何返回空数组?

问候

,因此解决方案是用:

初始化它。
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("%sn", json1) // null
fmt.Printf("%sn", json2) // []
fmt.Println(slice1 == nil) // true
fmt.Println(slice2 == nil) // false

Go Playground:https://play.golang.org/p/m9yeqypjldj

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

相关内容

最新更新