go - Golang Facebook 对 struct 的响应
问题描述
嗨,我是 GO 的新手,我正在尝试将 json 从 facebook api 转换为 struct。
问题是对象的键是动态的:
{
"100555213756790": {
"id": "100555213756790",
"about": "Noodle Bar & Restaurant",
"metadata": {
"fields": [
{
"name": "id",
"description": "asdasdasdasd",
"type": "numeric string"
},
//...
,
"101285033290986": {
"id": "101285033290986",
"about": "Smart City Expo World Congress",
"metadata": {
"fields": [
{
"name": "id",
"description": "fgddgdfgdg",
"type": "numeric string"
},
到目前为止我所取得的成就是通过 id 提取对象并将它们转换为地图:
for _, id := range ids {
fbPages, ok := results[string(id)].(map[string]interface{})
if ok {
for k, v := range fbPages {
fmt.Println(k)
fmt.Println(v)
}
}
}
//json to Page struct?
type Page struct {
ID string `json:"id"`
About string `json:"about"`
}
type Metadata struct {
Fields []Field `json:"fields"`
Type string `json:"type"`
Connections map[string]string `json:"connections"`
}
type Field struct {
Name string `json:"name"`
Description string `json:"description"`
Type *string `json:"type,omitempty"`
}
我的问题是:
如何将该地图转换为结构?或者有什么简单的方法可以做我想做的事吗?
谢谢
解决方案
将映射转换为结构:
import "github.com/mitchellh/mapstructure"
mapstructure.Decode(myMap, &myStruct)
但我会这样做:
type Page struct {
ID string `json:"id"`
About string `json:"about"`
//other fields and nested structs like your metadata struct
}
type fbPages map[string]Page
推荐阅读
- python - 字符串索引未在循环中更新
- maven - 如何根据需要构建具有任何版本的 Maven?
- python - 我想自动删除嵌入的触发器,我该怎么做?
- java - 在android中创建一个文本文件
- ms-access - 在 Access 中从另一个表中的列(运行总计)中减去一个表的列
- vba - 在 Word 中创建命令按钮以另存为,但文件格式必须启用宏
- javascript - 如何使用 material-ui 创建仪表板网格以进行反应?
- twitter - 如何在给定日期或推文时获取用户的 Twitter 关注者数量?
- regex - 用于将 API 过滤器编码为 URL 的 PowerShell 正则表达式
- python - 如何将多个列表中的相同索引添加到字典中