Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Parse JSON into nested structs

type APIResponse struct {
    Results []Result    `json:"results,omitempty"`
    Paging  Paging
}
type Result struct {
    Id string `json:"id"`,
    Name string `json:"name"`,
}
type Paging struct {
    Count    int    `json:"count"`
    Previous string `json:"previous"`
    Next     string `json:"next"`
}

func  Get(ctx context.Context) APIResponse[T] {
    results := APIResponse{}
    rc, Err := r.doRequest(ctx, req)
    if rc != nil {
        defer rc.Close()
    }
    err = json.NewDecoder(rc).Decode(&results)
    return results
}

The Sample JSON looks like this:

{
    "count": 70,
    "next": "https://api?page=2",
    "previous": null,
    "results": [
        {
            "id": 588,
            "name": "Tesco",
            }...

and I want it decoded into a struct of the form APIResponse, where the pagination element is a substruct, like the results is. However, in the sample JSON, the pagination aspect does not have a parent json tag. How can it be decoded into it’s own separate struct?

Currently, if I lift Count,Next, and Previous into the APIResponse, they appear, but they don’t appear when they’re a substruct.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Embed your Paging struct directly into APIResponse like:

type APIResponse struct {
    Results []Result    `json:"results,omitempty"`
    Paging
}
type Result struct {
    Id string `json:"id"`,
    Name string `json:"name"`,
}
type Paging struct {
    Count    int    `json:"count"`
    Previous string `json:"previous"`
    Next     string `json:"next"`
}

This way it will work as it defined in this structure. You can access its fields two ways:

  1. Directly:
    APIResponse.Count
  2. Indirect:
    APIResponse.Paging.Count
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading