35

So i have a struct :

type ProductConstructed struct {
    Name string `json:"Name"`
    BrandMedals []string `json:"BRAND_MEDALS"`
}

When i return my object with gin and :

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
}

It returns me :

null

instead of

[]

How to return an empty array ?

Regards

oguz ismail
  • 1
  • 16
  • 47
  • 69
Bussiere
  • 500
  • 13
  • 60
  • 119
  • You are using struct for response instead of array of struct so current output is accurate one. It seems from your code that you want to return only one struct at a time. So instead of handling it via empty array, handle it on null. – Manish Champaneri May 20 '19 at 06:54

2 Answers2

56

So the solution was to initialize it with :

productConstructed.BrandMedals = make([]string, 0)
Bussiere
  • 500
  • 13
  • 60
  • 119
20

Just to clarify why the solution above works:

slice1 is declared, but not defined. No variable has been assigned to it yet, it equals nil. When serialized, it will return null.

slice2 is declared and defined. It equals to an empty slice, not nil. When serialized, it will return [].

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

Go playground: https://play.golang.org/p/m9YEQYpJLdj

More info: https://github.com/golang/go/wiki/CodeReviewComments#declaring-empty-slices

frost
  • 1,003
  • 1
  • 12
  • 21