I'm writing an API wrapper where a call to the API returns a json response of some data, lets say:
{
group_id: 123,
group_name: "cool kids",
}
for the url example.com/api/groups
You can then append fields=members
to the url (so something like: example.com/api/groups?group_id=123&fields=members
) to then get:
{
members: [...some data..]
}
Note how the other fields are now missing...
Well I'm trying to use a single struct
which would look like:
type Club struct { GroupId int `json:"group_id"` GroupName string `json:"group_name"` Members []struct {...} `json:"members" }
This is what the structs look like:
type Committee struct {
GroupId string `json:"group_id"`
GroupName string `json:"group_name"`
Members []struct {
Person Person `json:"person"`
Rank float64 `json:"rank"`
Side string `json:"side"`
Title string `json:"title"`
} `json:"members"`
}
type Person struct {
id string `json:"id"`
name string `json:"name"`
age int `json:"age"`
}
func getGroup() Club {...}
func (c *Club) GetMembers() {...}
So I make the first call which unmarshals using getGroup
so the struct has GroupId
and GroupName
just fine and Members
is empty because the call didn't return anything for it.
I then call club.GetMembers()
to populate the Members
field so that the entire struct would be populated but it doesn't seem to be extracting it into the struct because at the end Members
is still empty and the data for GroupId
and GroupName
is still there.
I know for sure that the call is returning what I'm expecting so I figure it's Unmarshal
that isn't working so how would I go about this? Is this not within the functionality of Unmarshal
?
EDIT I just pushed the exact code to github, still unsure.
This is the repo: https://github.com/PeteJodo/gosun
This is a gist using the above repo: https://gist.github.com/PeteJodo/d5335b9f66304148483b
The main files of concern:
Alright so my issue has nothing to do with Unmarshal
per say. What was happening was that the API response returns:
{
results: [{
group_id: 123,
group_name: "cool kids"
}, ...],
...
}
...each result being an individual group. My problem was that each group was it's own struct and I had a method for the Group
struct that would make the next call to expand its Members
field, and I was using the Group
struct as the destination for Unmarshal
instead of something like Results
which would be structured correctly for the API response and THEN extract the correct Group
and its Members
field
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.