将 JSON 解析为嵌套结构

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
}

示例 JSON 如下所示:

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

我希望将其解码为 APIResponse 形式的结构,其中分页元素是一个子结构,就像结果一样。但是,在示例 JSON 中,分页方面没有父 json 标记。它如何被解码成它自己的独立结构?

目前,如果我将 Count、Next 和 Previous 提升到 APIResponse 中,它们会出现,但当它们是子结构时不会出现。

将您的 Paging 结构直接嵌入到 APIResponse 中,例如:

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"`
}

这样它就会像在这个结构中定义的那样工作。您可以通过两种方式访问​​其字段:

  1. 直接: APIResponse.Count
  2. 间接: APIResponse.Paging.Count