尝试将嵌套的json响应从2层深度压平为1层。
这是我在Go Playground上的工作代码:http://play.golang.org/p/kHAYuZUTko
我想最终得到:
type Social struct {
GooglePlusPlusOnes uint32 `Social:"GooglePlusOne"`
TwitterTweets uint32 `json:"Twitter"`
LinkedinShares uint32 `json:"LinkedIn"`
PinterestPins uint32 `json:"Pinterest"`
StumbleuponStumbles uint32 `json:"StumbleUpon"`
DeliciousBookmarks uint32 `json:"Delicious"`
FacebookLikes uint32 `json:"??some_magical_nested_address??"`
FacebookShares uint32 `json:"??some_magical_nested_address??"`
FacebookComments uint32 `json:"??some_magical_nested_address??"`
FacebookTotal uint32 `json:"??some_magical_nested_address??"`
}
...而不是包含嵌套的Facebook
类型的Social
类型(如下面的代码所示)。
我猜我需要编写一个自定义的UnmarshalJSON
函数,但我不知道它们是如何工作的,而且我对Go语言还很陌生。
有什么建议吗?
这是来自上面Go Playground链接的代码:
package main
import (
"encoding/json"
"fmt"
)
type Social struct {
GooglePlusPlusOnes uint32 `json:"GooglePlusOne"`
TwitterTweets uint32 `json:"Twitter"`
LinkedinShares uint32 `json:"LinkedIn"`
PinterestPins uint32 `json:"Pinterest"`
StumbleuponStumbles uint32 `json:"StumbleUpon"`
DeliciousBookmarks uint32 `json:"Delicious"`
Facebook Facebook
}
type Facebook struct {
FacebookLikes uint32 `json:"like_count"`
FacebookShares uint32 `json:"share_count"`
FacebookComments uint32 `json:"comment_count"`
FacebookTotal uint32 `json:"total_count"`
}
func main() {
var jsonBlob = []byte(`[
{"StumbleUpon":0,"Reddit":0,"Facebook":{"commentsbox_count":4691,"click_count":0,"total_count":298686,"comment_count":38955,"like_count":82902,"share_count":176829},"Delicious":0,"GooglePlusOne":275234,"Buzz":0,"Twitter":7346788,"Diggs":0,"Pinterest":40982,"LinkedIn":0}
]`)
var social []Social
err := json.Unmarshal(jsonBlob, &social)
if err != nil {
fmt.Println("error:", err)
}
fmt.Printf("%+v", social)
}