在 Golang 中以编程方式生成结构体
时间:2024-03-14
浏览:221
作者:佚名
哈喽!今天心血来潮给大家带来了《在 Golang 中以编程方式生成结构体》,想必大家应该对Golang都不陌生吧,那么阅读本文就都不会很困难,以下内容主要涉及到,若是你正在学习Golang,千万别错过这篇文章~希望能帮助到你!
问题内容
所以我正在使用一个外部 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"`
}
有什么办法,在解析输入时在 apiresponse 中定义 items 的类型。我不想为个人回复创建单独的类型。
基本上想要将任何传入响应解组到 apiresponse 结构中。
正确答案
将 items 字段的类型更改为 interface{}:
type apiresponse struct {
items interface{} `json:"items"`
...
}
将响应 items 字段设置为所需类型的指针。解组响应:
var articles []ArticleInfo
response := APIResponse{Items: &articles}
err := json.Unmarshal(data, &response)
使用变量 articles 访问文章。
Run an example on the playground。
到这里,我们也就讲完了《在 Golang 中以编程方式生成结构体》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.27
热门专题
