Search code examples
gogo-gingolang-migrate

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": [ {}, {} ] }


Solution

  • This is because your Subject uses lowercase fields name and section and thus will not be serialized.

    Changing it to:

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

    Will show the fields:

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