go - array of struct object not getting return in response
问题描述
My model having following data:
package main
type Subject struct {
name string `json:name`
section int `json:section`
}
var subjects = map[string][]Subject{
"1001": []Subject{
{
name: "Phy",
section: 1,
},
{
name: "Phy",
section: 2,
},
},
"1002": []Subject{
{
name: "Chem",
section: 1,
},
{
name: "Chem",
section: 2,
},
},
"1003": []Subject{
{
name: "Math",
section: 1,
},
{
name: "Math",
section: 2,
},
},
"1004": []Subject{
{
name: "Bio",
section: 1,
},
{
name: "Bio",
section: 2,
},
},
}
I am creating route as follows:
route.GET("/subjects/:id", func(c *gin.Context) {
id := c.Param("id")
subjects := subjects[id]
c.JSON(http.StatusOK, gin.H{
"StudentID": id,
"Subject": subjects,
})
})
It tried to call it using postman as : localhost:8080/subjects/1001 but it just shows {} {} instead of array of subject struct's objects.
Output: { "StudentID": "1001", "Subject": [ {}, {} ] }
解决方案
这是因为您Subject
使用小写字段name
,section
因此不会被序列化。
将其更改为:
type Subject struct {
Name string `json:"name"`
Section int `json:"section"`
}
将显示以下字段:
{
"StudentID": "1001",
"Subject": [
{"name":"Phy","section":1},
{"name":"Phy","section":2}
]
}
推荐阅读
- html - 为 ngb-tabset 创建自定义 CSS 设计
- amazon-web-services - Jenkins 用户名和密码错误(电子邮件通知)
- mysql - 用于 MySql 函数的 SimpleJdbcCall 产生“无法为存储的函数调用的返回值设置 IN 参数”
- javascript - 在两个控制器中调用一个函数 - AngularJS 1.x
- django - Django:管理中的网址而不是图片
- java - 如何从 CSV 文件中跳线
- angularjs - 当我们在单个页面中放置多个 `ng-init` 时会出现任何问题(多个部分页面的组合)
- tensorflow - 如何在训练 Tensorflow 对象检测 API 时获取训练输入数据?
- drools - 如何将当前事件与 Drools 中的先前事件进行比较?
- objective-c - 使用旋转绘制标签时如何解决平移问题