我试图返回array []Employee作为响应。Is具有len 2。但postman显示响应体为空。
type People struct {
Height int32 `json:"height" binding:"required"`
Weight int32 `json:"weight" binding:"required"`
}
type Employee struct {
Salary int `json:"salary"`
People
}
c.JSON(http.StatusOK, employeeArray)
我在google里发现golang有一些内部绑定结构的问题。
UPD:使用MarshalJSON重写的代码。
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
type TypeName struct {
Name string `json:"name" binding:"required"`
}
func (p TypeName) MarshalJSON() ([]byte, error) {
return []byte("Joe"), nil
}
type People struct {
Height int32 `json:"height" binding:"required"`
Weight int32 `json:"weight" binding:"required"`
TypeName
}
type Employee struct {
Salary int `json:"salary"`
People
}
func main() {
r := gin.Default()
r.GET("/employees", func(c *gin.Context) {
employeeArray := []Employee{
{
Salary: 10000,
People: People{
Height: 170,
Weight: 80,
},
},
{
Salary: 20000,
People: People{
Height: 175,
Weight: 80,
},
},
}
c.JSON(http.StatusOK, employeeArray)
})
_ = r.Run()
}
1条答案
按热度按时间jgwigjjp1#
[]byte("Joe")
不是一个有效的json。它应该被引用。如果你注意gin的日志,你应该在那里看到一个错误消息:Error #01: json: error calling MarshalJSON for type main.Employee: invalid character 'J' looking for beginning of value
。这个应该可以工作:下面是
time.Time
的演示: