首页 > 解决方案 > 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"`
    }

我的问题是:

如何将该地图转换为结构?或者有什么简单的方法可以做我想做的事吗?

谢谢

标签: gostruct

解决方案


将映射转换为结构:

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

推荐阅读