[英]Golang, Decoding json into custom structure
我正在尝试将json API中的reddit内容提取到客户端的自定义结构中。 我想出的结构是
type Subreddit struct {
offset int
num_of_posts int
subscribers: int
thumbnail string
children []post
}
type post struct {
type string
url string
thumbnail string
submitted_by string
upvotes int
downvotes int
}
不幸的是reddit json甚至没有被格式化,此外,我还要过滤掉我不支持的url等。
我唯一知道的方法是为源数据中的每个“孩子”创建一个接口,并手动遍历每个孩子,为每个接口创建一个单独的“帖子”。 并将它们推入subreddit对象的post数组中。
供参考,数据格式如http://www.reddit.com/r/web_design/.json
这是正确的方法吗? 还是有更快的方法。 这么小的任务似乎要花很多钱,但是我是PHP Javascript开发人员,所以我认为这对我来说很不寻常。
在我开始回答这个问题之前:
请记住,必须导出您的struct字段才能与encoding/json
包一起使用。
其次,我必须承认,我不太确定您对整个create an interface for each of the "children"
部分create an interface for each of the "children"
含义。 但这听起来很复杂;)
无论如何,对您的答案:
如果您希望使用标准的encoding/json
包解组json,则必须使用中间结构,除非您使用与Reddit使用的结构相似的结构。
在下面,您可以找到有关Reddit结构的某些部分如何映射到Go结构的示例。 通过将json解组到RedditRoot的实例中,您可以轻松地在Children上进行迭代,删除任何不需要的子代并填充Subreddit结构:
type RedditRoot struct {
Kind string `json:"kind"`
Data RedditData `json:"data"`
}
type RedditData struct {
Children []RedditDataChild `json:"children"`
}
type RedditDataChild struct {
Kind string `json:"kind"`
Data *Post `json:"data"`
}
type Post struct {
Type string `json:"-"` // Is this equal to data.children[].data.kind?
Url string `json:"url"`
Thumbnail string `json:"thumbnail"`
Submitted_by string `json:"author"`
Upvotes int `json:"ups"`
Downvotes int `json:"downs"`
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.