在Golang中动态创建结构体

huangapple go评论83阅读模式
英文:

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访问文章。

在 playground 上运行示例

英文:

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.

Run an example on the playground.

huangapple
  • 本文由 发表于 2022年2月19日 00:36:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/71176935.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定