Golang,将json解码为自定义结构
I'm trying to pull reddit content from the json API into a custom structure for the client. the structure i've come up with in go for this is
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
}
unfortunately the reddit json isn't formatted even close to this and in addition i'll want to filter out url's i can't support etc.
The only way i know to do it this is to create an interface for each of the "children" in the source data, and iterate through each child manually, creating an individual "post" for each interface. and pushing them into the subreddit object's post array.
For reference the data is formatted like http://www.reddit.com/r/web_design/.json
Is this the right way to do this? Or is there a faster way. It seems like a lot of overhead for such a small task, but i'm a PHP Javascript dev, so It's just unusual for me I suppose.
我正在尝试将json API中的reddit内容提取到客户端的自定义结构中。 我为此准备的结构是 p>
type Subreddit struct {
offset int
num_of_posts int
订阅者:int
缩略图字符串
子项[] post
}
type post struct {
输入字符串
url字符串
缩略图字符串
Submitted_by字符串
投票int
投票int
}
code> pre >
不幸的是,reddit json的格式甚至不接近此格式,此外,我还要过滤掉我不支持的url等。 p>
The 我知道要做的唯一方法是为源数据中的每个“孩子”创建一个接口,并手动遍历每个孩子,为每个接口创建一个单独的“帖子”。 并将它们推入subreddit对象的post数组中。 p>
供参考,数据格式如 http:// www.reddit.com/r/web_design/.json p>
这是正确的方法吗? 还是有更快的方法。 这么小的任务似乎要花很多钱,但是我是PHP Javascript开发人员,所以我认为这对我来说很不寻常。 p>
div>
Before I even start to answer the question:
Remember that your struct fields must be exported in order to be used with the encoding/json
package.
Secondly I must admit I am not entirely sure what you meant with the entire create an interface for each of the "children"
part. But it sounded complicated ;)
Anyway, to your answer:
If you wish to use the standard encoding/json
package to unmarshal the json, you must use an intermediate structure unless you will use a similar structure as the one used by Reddit.
Below you can find an example of how parts of the Reddit structure might be mapped to Go structs. By Unmarshalling the json into an instance of RedditRoot, you can then easily iterate over the Children , remove any unwanted child, and populate your Subreddit struct:
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"`
}