所以我有一个结构:
type ProductConstructed struct {
Name string `json:"Name"`
BrandMedals []string `json:"BRAND_MEDALS"`
}
Run Code Online (Sandbox Code Playgroud)
当我用杜松子酒返回我的对象时:
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
}
Run Code Online (Sandbox Code Playgroud)
它返回我:
空值
代替
[]
如何返回一个空数组?
问候
fro*_*ost 23
只是为了澄清为什么上述解决方案有效:
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
Run Code Online (Sandbox Code Playgroud)
去游乐场:https://play.golang.org/p/m9YEQYpJLdj
更多信息:https://github.com/golang/go/wiki/CodeReviewComments#declaring-empty-slices
use*_*794 15
所以解决方案是用以下方法初始化它:
productConstructed.BrandMedals = make([]string, 0)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6588 次 |
| 最近记录: |