How to set an array in json response goLang-gin

huangapple go评论71阅读模式
英文:

How to set an array in json response goLang-gin

问题

我有一个存储在变量myArray中的结构体数组。

结构体定义如下:

type myStruct struct {
    id     int64  `db:"id" json:"id"`
    Name   string `form:"name" db:"name" json:"name" binding:"required"`
    Status string `form:"status" db:"status" json:"status" binding:"required"`
}

我的数组看起来像这样,并存储在变量'myArray'中。这个数组是通过迭代从数据库中获取的一组行来形成的。

[{1 abc default} {2 xyz default}]

我正在使用gin作为HTTP服务器。如何使用c.JSON将这个数组设置为JSON响应,类似于以下格式:

[
   {
      "id": 1,
      "name": "abc",
      "status": "default"
   },
   {
      "id": 2,
      "name": "xyz",
      "status": "default"
   }
]
英文:

I have an array of stucts stored a variable my array.

Struct is

  type myStruct struct {
    id          int64   `db:"id" json:"id"`
    Name        string  `form:"name" db:"name" json:"name" binding:"required"`
    Status     string     `form:"status"  db:"status" json:"status" binding:"required"`

My array looks like this and is stored in a variable 'myArray'. This array is formed by iterating over a set of rows coming from database.

[{1 abc default} {2 xyz default}]

I am using gin as http server. How do I set this array into JSON reponse using c.JSON. Something like

[
   {
      id: 1,
      name : 'abc' 
      status: 'default'
   },
   {
      id: 2,
      name : 'xyz' 
      status: 'default'
   }
]

答案1

得分: 4

好的,以下是翻译好的内容:

好的,c.JSON(http.StatusOK, myArray) 工作正常。但是我在响应中看不到 Id 字段。有什么原因吗?是因为 'int64' 数据类型吗?

英文:

ok c.JSON(http.StatusOK, myArray) worked. But I cannot see the Id field in the response. Any reason why? Is it because of 'int64' dataType?

huangapple
  • 本文由 发表于 2016年8月23日 15:59:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/39095502.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定