Golang:Gin框架中在http响应时返回数组不起作用

u5i3ibmn  于 2023-04-27  发布在  Go
关注(0)|答案(1)|浏览(174)

我试图返回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()
}
jgwigjjp

jgwigjjp1#

func (p TypeName) MarshalJSON() ([]byte, error) {
    return []byte("Joe"), nil
}

[]byte("Joe")不是一个有效的json。它应该被引用。如果你注意gin的日志,你应该在那里看到一个错误消息:Error #01: json: error calling MarshalJSON for type main.Employee: invalid character 'J' looking for beginning of value。这个应该可以工作:

func (p TypeName) MarshalJSON() ([]byte, error) {
    return []byte(`"Joe"`), nil
}

下面是time.Time的演示:

package main

import (
    "net/http"
    "time"

    "github.com/gin-gonic/gin"
)

type Time struct {
    StandardTime time.Time
}

func (p Time) MarshalJSON() ([]byte, error) {
    timeString := p.StandardTime.Format(time.RFC3339)
    return json.Marshal(timeString)
}

func main() {
    r := gin.Default()

    r.GET("/time", func(c *gin.Context) {
        timeArray := []Time{
            {
                StandardTime: time.Now(),
            },
            {
                StandardTime: time.Now().Add(30 * time.Minute),
            },
        }

        c.JSON(http.StatusOK, timeArray)
    })
    _ = r.Run()
}

相关问题