首页 > 解决方案 > array of struct object not getting return in response

问题描述

My model having following data:

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,
        },
    },
}

I am creating route as follows:

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,
        })
    })

It tried to call it using postman as : localhost:8080/subjects/1001 but it just shows {} {} instead of array of subject struct's objects.

Output: { "StudentID": "1001", "Subject": [ {}, {} ] }

标签: gogo-gingolang-migrate

解决方案


这是因为您Subject使用小写字段namesection因此不会被序列化。

将其更改为:

type Subject struct {
    Name    string `json:"name"`
    Section int    `json:"section"`
}

将显示以下字段:

{
  "StudentID": "1001",
  "Subject": [
    {"name":"Phy","section":1},
    {"name":"Phy","section":2}
  ]
}

推荐阅读