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

问题描述 投票:0回答:1

我正在尝试返回数组 []Employee 作为响应。有 len 2。但是邮递员显示响应主体是空的。

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()
}
go
1个回答
1
投票
func (p TypeName) MarshalJSON() ([]byte, error) {
    return []byte("Joe"), nil
}

[]byte("Joe")
不是有效的 json。应该引用它。

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 []byte(`"` + timeString + `"`), nil
}

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()
}
© www.soinside.com 2019 - 2024. All rights reserved.