亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將 JSON 解析為嵌套結構

將 JSON 解析為嵌套結構

Go
明月笑刀無情 2022-12-19 10:43:53
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 中,它們會出現,但當它們是子結構時不會出現。
查看完整描述

1 回答

?
慕婉清6462132

TA貢獻1804條經驗 獲得超2個贊

將您的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


查看完整回答
反對 回復 2022-12-19
  • 1 回答
  • 0 關注
  • 114 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號