登录
首页 >  Golang >  Go问答

用 Golang 将 JSON 编码为结构体切片

来源:stackoverflow

时间:2024-03-23 23:21:30 367浏览 收藏

推广推荐
免费电影APP ➜
支持 PC / 移动端,安全直达

本文讨论了使用 Go 语言将 JSON 编码为结构体切片的问题。在解析通过 API 发送的 JSON 正文时,需要通过 JSON 传递一个结构数组,而不是对等名 JSON 对象。文章提供了一个示例 JSON 请求和 Go 语言结构体,以说明正确的语法。

问题内容

我正在编写一个简单的 post api 请求。我能够将 json 解析为 golang 结构,直到对等名 json 对象。我不知道通过 api 的 json 主体传递值来填充结构的 golang 切片的正确语法。

我正在尝试解析通过 api 发送的 json 正文。这是正文请求示例 -

{  
   "type":"string",
   "name":"string",
   "organization":{  
      "orgid":"1",
      "orgname":"string",
      "peer":{  
         "peerid":"1",
         "peername":"string"
      },
      "attributes":[
    ["slide0001.html", "looking ahead"],
    ["slide0008.html", "forecast"],
    ["slide0021.html", "summary"]
]
    }
} "peername":"string"
          },
          "attributes":["name":"string":"value":true]
        }
    }

这是我的示例 golang 结构。

//Identity ...
type Identity struct {
    Type         string        `json:"type,omitempty"`
    Name         string        `json:"name,omitempty"`
    Organization *Organization `json:"organization,omitempty"`
}

//Organization ....
type Organization struct {
    OrgID      string      `json:"orgID,omitempty"`
    OrgName    string      `json:"orgName,omitempty"`
    Peer       *Peer       `json:"peer,omitempty"`
    Attributes *Attributes `json:"attributes"`
}

//Peer ...
type Peer struct {
    PeerID   string `json:"peerID,omitempty"`
    PeerName string `json:"peerName,omitempty"`
}

//Attributes ...
type Attributes []struct {
    Name  string `json:"name"`
    Value bool   `json:"value"`
}

解决方案


终于弄清楚了正确的语法。我们必须通过 json 传递一个结构数组。

{  
   "type":"string",
   "name":"string",
   "organization":
   {  
      "orgID":"1",
      "orgName":"string",
      "peer":
      {  
         "peerID":"1",
         "peerName":"string"
      },
      "attributes":
      [
        {"slide0001.html": "Looking Ahead"},
        {"slide0008.html": "Forecast"},
        {"slide0021.html": "Summary"}
      ]
    }
}

今天关于《用 Golang 将 JSON 编码为结构体切片》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>