所以我正在使用一个外部 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 结构中。
1 回答

智慧大石
TA贡献1946条经验 获得超3个赞
Items将字段类型更改为interface{}:
type APIResponse struct {
Items interface{} `json:"items"`
...
}
将响应Items字段设置为所需类型的指针。解组响应:
var articles []ArticleInfo
response := APIResponse{Items: &articles}
err := json.Unmarshal(data, &response)
使用变量访问文章articles。
- 1 回答
- 0 关注
- 275 浏览
添加回答
举报
0/150
提交
取消