首页 > golang - 解析复杂json

golang - 解析复杂json

代码在这里 http://play.golang.org/p/l1__b2FOsv

// 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": "@"
      },
      {
        "value": "us2.mx1.mailhostbox.com.",
        "ttl": 1,
        "priority": 100,
        "hostName": "@"
      },
      {
        "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)

}

解析出来data为空,这是为何?
不用interface该如何解析


只有首字母大写的 struct field 才能被 encoding/json 库识别。


go 里面解析 json 由于大小写问题变得极度蛋疼,以前我做 facebook 接口开发的时候不能忍受总是在写 json:"xxx" 的代码索性自己写了个非常强大的解析库,你或许可以试试。

注意,这个库是为 facebook 接入而写的,所以名字叫 facebook,但其中关于 json 的那一块是完全独立的,可以单独使用。

项目地址:https://github.com/huandu/facebook

示例代码:

package main

import (
    "encoding/json"
    fb "github.com/huandu/facebook"
)

type Foo struct {
    TestField string
    Other     int    `facebook:"another"`
}

func main() {
    str = `{
        "test_field": "hello",
        "another": 123,
        "data": [
            {"test_field": "world!"}
        ]
    }`
    var result fb.Result
    json.Unmarshal([]byte(str), &result)

    // Now, we can play with json structure freely!
    var foo Foo
    result.Decode(&foo)                // works!
    result.DecodeField("data.0", &foo) // works!
}

具体实现方法其实很简单粗暴,就是遍历 map[string]interface{} 所有元素,然后检查每个 interface{} 类型是否能够转换成目标类型,有大量的 switch...case。具体可以看 result.go 的实现。


struct里各个字段的大小写问题,encoding/json默认只认首字母大写的字段。
你的DataMxRecords全是首字母小写的字段,又没加上类似json:"status"这样的强制说明,解析出来就是空的
个人推荐JSON解析用第三方库,比如https://github.com/bitly/go-simplejson

【热门文章】
【热门文章】