Golang Facebook对结构的回应

时间:2018-07-30 08:37:42

标签: go 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"`
    }

我的问题是:

如何将该映射转换为struct?还是有什么简单的方法可以做我想做的事情?

谢谢

1 个答案:

答案 0 :(得分:1)

将地图转换为结构:

import "github.com/mitchellh/mapstructure"

mapstructure.Decode(myMap, &myStruct)

example

但是我会这样做:

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