英文:
Dynamically Create Structs in Golang
问题
所以我正在使用一个外部API,我想要解析其响应。传入的响应是固定格式的,即:
type APIResponse struct {
Items []interface{} `json:"items"`
QuotaMax int `json:"quota_max"`
QuotaRemaining int `json:"quota_remaining"`
}
因此,对于每个响应,我都在解析items。现在,根据请求,items可以是不同类型的。它可以是站点、文章等的切片。它们都有各自的模型,例如:
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"`
}
有没有办法在解析输入时定义APIResponse中Items的类型?我不想为每个响应创建单独的类型。基本上想要将任何传入的响应解组为APIResponse结构体。
英文:
So I am working with an external API, whose responses I wanted to parse. The incoming responses are of a fixed format i.e.
type APIResponse struct {
Items []interface{} `json:"items"`
QuotaMax int `json:"quota_max"`
QuotaRemaining int `json:"quota_remaining"`
}
So for each response I am parsing the items. Now the items can be of diff types as per the request. It can be a slice of sites, articles, etc. Which have their individual models. like:
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"`
}
Is there any way, when parsing the input define the type of Items
in APIResponse. I don't want to create separate types for individual responses.
Basically want to Unmarshall any incoming response into the APIResponse struct.
答案1
得分: 1
将Items
字段的类型更改为interface{}
:
type APIResponse struct {
Items interface{} `json:"items"`
...
}
将响应的Items
字段设置为所需类型的指针。将数据解组到响应中:
var articles []ArticleInfo
response := APIResponse{Items: &articles}
err := json.Unmarshal(data, &response)
使用变量articles
访问文章。
英文:
Change type of the Items
field to interface{}
:
type APIResponse struct {
Items interface{} `json:"items"`
...
}
Set the response Items
field to pointer of the desired type. Unmarshal to the response:
var articles []ArticleInfo
response := APIResponse{Items: &articles}
err := json.Unmarshal(data, &response)
Access the articles using variable articles
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论