所以我正在使用一個外部 API,我想決議它的回應。傳入的回應具有固定格式,即
type APIResponse struct {
Items []interface{} `json:"items"`
QuotaMax int `json:"quota_max"`
QuotaRemaining int `json:"quota_remaining"`
}
因此,對于每個回應,我都在決議專案。現在專案可以根據請求是不同型別的。它可以是網站、文章等的一部分,它們有各自的模型。喜歡:
type ArticleInfo struct {
ArticleId uint64 `json:"article_id"`
ArticleType string `json:"article_type"`
Link string `json:"link"`
Title string `json:"title"`
}
type SiteInfo struct {
Name string `json:"name"`
Slug string `json:"slug"`
SiteURL string `json:"site_url"`
}
有什么辦法,在決議輸入時定義ItemsAPIResponse 的型別。我不想為單個回應創建單獨的型別。基本上想將任何傳入的回應解組到 APIResponse 結構中。
uj5u.com熱心網友回復:
Items將欄位型別更改為interface{}:
type APIResponse struct {
Items interface{} `json:"items"`
...
}
將回應Items欄位設定為所需型別的指標。解組回應:
var articles []ArticleInfo
response := APIResponse{Items: &articles}
err := json.Unmarshal(data, &response)
使用變數訪問文章articles。
在操場上運行一個示例。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/429832.html
