如何将json解码为结构

编程入门 行业动态 更新时间:2024-10-25 00:28:14
本文介绍了如何将json解码为结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试在Go中解码一些json,但是某些字段没有被解码. 请参见此处:

I'm trying to decode some json in Go but some fields don't get decoded. See the code running in browser here:

我在做什么错了?

我只需要MX记录,所以我没有定义其他字段.据我从godoc了解到,您不需要定义不需要/不需要的字段.

I need only the MX records so I didn't define the other fields. As I understand from the godoc you don't need to define the fields you don't use/need.

// You can edit this code! // Click here and start typing. package main import "fmt" import "encoding/json" func main() { body := ` {"response": { "status": "SUCCESS", "data": { "mxRecords": [ { "value": "us2.mx3.mailhostbox.", "ttl": 1, "priority": 100, "hostName": "@" }, { "value": "us2.mx1.mailhostbox.", "ttl": 1, "priority": 100, "hostName": "@" }, { "value": "us2.mx2.mailhostbox.", "ttl": 1, "priority": 100, "hostName": "@" } ], "cnameRecords": [ { "aliasHost": "pop.a.co.uk.", "canonicalHost": "us2.pop.mailhostbox." }, { "aliasHost": "webmail.a.co.uk.", "canonicalHost": "us2.webmail.mailhostbox." }, { "aliasHost": "smtp.a.co.uk.", "canonicalHost": "us2.smtp.mailhostbox." }, { "aliasHost": "imap.a.co.uk.", "canonicalHost": "us2.imap.mailhostbox." } ], "dkimTxtRecord": { "domainname": "20a19._domainkey.a.co.uk", "value": "\"v=DKIM1; g=*; k=rsa; p=DkfbhO8Oyy0E1WyUWwIDAQAB\"", "ttl": 1 }, "spfTxtRecord": { "domainname": "a.co.uk", "value": "\"v=spf1 redirect=_spf.mailhostbox\"", "ttl": 1 }, "loginUrl": "us2.cp.mailhostbox" } }}` type MxRecords struct { value string ttl int priority int hostName string } type Data struct { mxRecords []MxRecords } type Response struct { Status string `json:"status"` Data Data `json:"data"` } type apiR struct { Response Response } var r apiR err := json.Unmarshal([]byte(body), &r) if err != nil { fmt.Printf("err was %v", err) } fmt.Printf("decoded is %v", r) }

推荐答案

根据有关 json的转到文档,取消编组,您只能对导出的字段进行解码,主要原因是外部程序包(例如encoding/json)无法访问未导出的字段.

As per the go documentaiton about json.Unmarshal, you can only decode toward exported fields, the main reason being that external packages (such as encoding/json) cannot acces unexported fields.

如果您的json不遵循名称的go约定,则可以在字段中使用json标记来更改json键和struct字段之间的匹配.

If your json doesn't follow the go convention for names, you can use the json tag in your fields to change the matching between json key and struct field.

示例:

package main import ( "fmt" "encoding/json" ) type T struct { Foo string `json:"foo"` } func main() { text := []byte(`{"foo":"bar"}`) var t T err := json.Unmarshal(text, &t) if err != nil { panic(err) } fmt.Println(t) }

更多推荐

如何将json解码为结构

本文发布于:2023-08-03 08:08:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1285495.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何将   结构   json

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!