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

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

試圖從 JSON 響應中獲取“Total”的值

試圖從 JSON 響應中獲取“Total”的值

Go
動漫人物 2022-06-21 10:42:43
回復:{“元”:{“查詢時間”:0.039130201,“分頁”:{“偏移”:1345,“限制”:5000,“總計”:1345},結構:類型 InLicense 結構 {Total int16 json:"total,omitempty"}類型 OutLicense 結構 {分頁 []InLicense json:"pagination,omitempty"}類型 MetaLicense 結構 {Meta []OutLicense json:"meta,omitempty"}函數內部的代碼片段:req, err := http.NewRequest("GET", , nil)if err != nil {//處理錯誤}client := &http.Client{}resp, err := client.Do(req)if err != nil {log.Println("Error: ", err)}defer resp.Body.Close()val := &MetaLicense{ }err = json.NewDecoder(resp.Body).Decode(&val)if err != nil {    log.Fatal(err)}for _, s := range val.Meta {    for _, a := range s.Pagination {        fmt.Println(a.Total)    }}}運行此代碼后,出現以下錯誤: json: cannot unmarshal object into Go struct field MetaLicense.meta of type []OutLicense[]OutLicense 需要哪種類型才能正確解組?我無法以其他方式打印它,但它使用 {} 打印,并且 Strings.Trim 不起作用。
查看完整描述

2 回答

?
一只萌萌小番薯

TA貢獻1795條經驗 獲得超7個贊

您應該只使用具有實際類型的簡單字段聲明,而不是[]如下所示的類型:


type InLicense struct {

    Total int16 json:"total,omitempty"

}


type OutLicense struct {

     Pagination InLicense json:"pagination,omitempty"

}


type MetaLicense struct {

    Meta OutLicense json:"meta,omitempty"

}


查看完整回答
反對 回復 2022-06-21
?
九州編程

TA貢獻1785條經驗 獲得超4個贊

我稍微簡化了解析,只使用了該json.Unmarshal()函數。


raw := "{\n  \"meta\": {\n    \"query_time\": 0.039130201,\n    \"pagination\": {\n      \"offset\": 1345,\n      \"limit\": 5000,\n      \"total\": 1345\n    }\n  }\n}"


parsed := &MetaLicense{}

err := json.Unmarshal([]byte(raw), parsed)

if err != nil {

    log.Fatal(err)

}


fmt.Println(parsed.Meta.Pagination.Total) // Prints: 1345

這是我使用的類型


type InLicense struct {

    Total int16 `json:"total,omitempty"`

}


type OutLicense struct {

    Pagination InLicense `json:"pagination,omitempty"`

}


type MetaLicense struct {

    Meta OutLicense `json:"meta,omitempty"`

}

如所寫,您提供的 JSON 有一個額外的,內容,這使您的 json 無法解析(假設您也添加了缺少}的 's.


您的 JSON 中沒有列表。列表用[]符號表示。為了讓您的類型正常工作,您的 JSON 必須如下所示:


{

  "meta": [{

    "query_time": 0.039130201,

    "pagination": [{

      "offset": 1345,

      "limit": 5000,

      "total": 1345

    }]

  }]

}


查看完整回答
反對 回復 2022-06-21
  • 2 回答
  • 0 關注
  • 278 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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