英文:
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的结构体,其中分页元素是一个子结构,就像results一样。然而,在示例JSON中,分页部分没有父级json标签。如何将其解码为一个单独的结构体?
目前,如果我将Count、Next和Previous提升到APIResponse中,它们会出现,但当它们是子结构时,它们不会出现。
英文:
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.
答案1
得分: 1
将你的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
英文:
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:
- Directly:
APIResponse.Count
- Indirect:
APIResponse.Paging.Count
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论