【问题标题】:Return an empty array instead of null with golang for json return with gin使用golang返回一个空数组而不是null,以便使用gin返回json
【发布时间】:2019-10-05 15:25:25
【问题描述】:

所以我有一个结构:

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
}

它返回我:

而不是

[]

如何返回一个空数组?

问候

【问题讨论】:

  • 您正在使用 struct 进行响应,而不是 struct 数组,因此当前输出是准确的。从您的代码看来,您一次只想返回一个结构。因此,不要通过空数组处理它,而是在 null 上处理它。

标签: json go go-gin


【解决方案1】:

所以解决方案是用 : 来初始化它:

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

【讨论】:

  • productConstructed.BrandMedals = []string{}也可以
  • @Seaskyways 您的解决方案更加优雅易懂,谢谢
  • 100% 等效,只是语法不同
【解决方案2】:

只是为了澄清为什么上述解决方案有效:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-21
    • 2019-05-14
    • 2020-05-15
    • 1970-01-01
    • 1970-01-01
    • 2020-07-15
    • 2021-07-22
    相关资源
    最近更新 更多