go 语言解析复杂json

u010499721 · · 5904 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

// Click here and start typing.
package main

import "fmt"
import "encoding/json"

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 `json:"response"`
}

func main() {

	body := `
  {"response": {
  "status": "SUCCESS",
  "data": {
    "mxRecords": [
      {
        "value": "us2.mx3.mailhostbox.com.",
        "ttl": 1,
        "priority": 100,
        "hostName": "hostname@"
      },
      {
        "value": "us2.mx1.mailhostbox.com.",
        "ttl": 1,
        "priority": 100,
        "hostName": "hostnam233e@"
      },
      {
        "value": "us2.mx2.mailhostbox.com.",
        "ttl": 1,
        "priority": 100,
        "hostName": "@"
      }
    ],
    "cnameRecords": [
      {
        "aliasHost": "pop.a.co.uk.",
        "canonicalHost": "us2.pop.mailhostbox.com."
      },
      {
        "aliasHost": "webmail.a.co.uk.",
        "canonicalHost": "us2.webmail.mailhostbox.com."
      },
      {
        "aliasHost": "smtp.a.co.uk.",
        "canonicalHost": "us2.smtp.mailhostbox.com."
      },
      {
        "aliasHost": "imap.a.co.uk.",
        "canonicalHost": "us2.imap.mailhostbox.com."
      }
    ],
    "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.com\"",
      "ttl": 1
    },
    "loginUrl": "us2.cp.mailhostbox.com"
  }
}}`

	var r apiR
	err := json.Unmarshal([]byte(body), &r)
	if err != nil {
		fmt.Printf("err was %v", err)
	}

	fmt.Println(r.Response.Data.MxRecords[1].HostName)

}



参考:

http://segmentfault.com/q/1010000000583211     (原文问题,字段转大写即可)

http://my.oschina.net/golang/blog/210012


有疑问加站长微信联系(非本文作者)

本文来自:CSDN博客

感谢作者:u010499721

查看原文:go 语言解析复杂json

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

5904 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传