结构对象数组没有得到 return 作为响应
array of struct object not getting return in response
我的模型有以下数据:
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",
“学科”: [
{},
{}
]
}
这是因为您的 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}
]
}
我的模型有以下数据:
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", “学科”: [ {}, {} ] }
这是因为您的 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}
]
}