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"`
}
这样,它将按照此结构中定义的方式工作。您可以通过两种方式访问其字段:
APIResponse.Count
APIResponse.Paging.Count
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句