【发布时间】:2021-04-30 21:57:23
【问题描述】:
我的模型有以下数据:
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,
},
},
}
我正在创建如下路线:
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,
})
})
它试图使用邮递员调用它:localhost:8080/subjects/1001 但它只显示 {} {} 而不是主题结构的对象数组。
输出: { "学生证": "1001", “主题”: [ {}, {} ] }
【问题讨论】:
-
您需要导出字段,以便
json包可以对其进行编码,例如Name和Section与name和section。如果您希望它们在响应中为小写,您可以使用 json 标记,例如Name string `json: "name"`.
标签: go go-gin golang-migrate