栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

将GoLang中的JSON解析为struct

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

将GoLang中的JSON解析为struct

您的

ParseResponse
函数存在问题,您正在调用
json.Unmarshal
作为第一个参数传递
json
,这是一个包名:这是模棱两可的。

如您所见,代码可以很好地更改

ParseResponse
函数。

package mainimport (    "encoding/json"    "fmt")type gateway struct {    Characteristics       []string      `json:"characteristics"`    CreatedAt  string        `json:"created_at"`    Credentials[]interface{} `json:"credentials"`    Descriptioninterface{}   `json:"description"`    GatewaySpecificFields []interface{} `json:"gateway_specific_fields"`    GatewayTypestring        `json:"gateway_type"`    Name       string        `json:"name"`    PaymentMethods        []string      `json:"payment_methods"`    Redacted   bool          `json:"redacted"`    State      string        `json:"state"`    Token      string        `json:"token"`    UpdatedAt  string        `json:"updated_at"`}type gateways struct {    Gateways []gateway `json:"gateways"`}func ParseResponse(js []byte) {    var parsed gateways    json.Unmarshal(js, &parsed)    fmt.Println(parsed)}func main() {    var js []byte = []byte(`{"gateways": [    {        "token": "my_token_here",        "gateway_type": "test",        "description": null,        "payment_methods": [ "credit_card", "sprel", "third_party_token", "bank_account", "apple_pay"        ],        "state": "retained",        "created_at": "2016-03-12T18:52:37Z",        "updated_at": "2016-03-12T18:52:37Z",        "name": "Spreedly Test",        "characteristics": [ "purchase", "authorize", "capture", "credit", "general_credit", "void", "verify", "reference_purchase", "purchase_via_preauthorization", "offsite_purchase", "offsite_authorize", "3dsecure_purchase", "3dsecure_authorize", "store", "remove", "disburse", "reference_authorization"        ],        "credentials": [],        "gateway_specific_fields": [],        "redacted": false    }]}`)        ParseResponse(js)}

输出:

{[{[purchase authorize capture credit general_credit void verify reference_purchase purchase_via_preauthorization offsite_purchase offsite_authorize 3dsecure_purchase 3dsecure_authorize store remove disburse reference_authorization] 2016-03-12T18:52:37Z [] <nil> [] test Spreedly Test [credit_card sprel third_party_token bank_account apple_pay] false retained my_token_here 2016-03-12T18:52:37Z}]}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/371376.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号