2016-12-28 69 views
-1

解组JSON我有一个JSON:如何在golang

{"code":200, 
"msg":"success", 
"data":{"url":"https:\/\/mp.weixin.qq.com\/cgi-bin\/showqrcode?ticket=gQHQ7jwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyX3pqS0pMZlA4a1AxbEJkemhvMVoAAgQ5TGNYAwQsAQAA"}} 

和我定义一个结构:

type Result struct { 
    code int 
    msg string     `json:"msg"` 
    data map[string]interface{} `json:"data"` 
} 

此代码:

var res Result 
json.Unmarshal(body, &res) 
fmt.Println(res) 

输出是:{0 map[]}

我想得到urldata,如何得到它?

回答

1

你应该资本化领域的第一个字母(CodeMsgData)访问导出字段(codemsgdata)为Result(设置/获取),其中:

package main 

import (
    "encoding/json" 
    "fmt" 
) 

type Result struct { 
    Code int     `json:"code"` 
    Msg string     `json:"msg"` 
    Data map[string]interface{} `json:"data"` 
} 

func main() { 
    str := `{"code":200,"msg":"success","data":{"url":"https:\/\/mp.weixin.qq.com\/cgi-bin\/showqrcode?ticket=gQHQ7jwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyX3pqS0pMZlA4a1AxbEJkemhvMVoAAgQ5TGNYAwQsAQAA"}}` 
    var res Result 
    err := json.Unmarshal([]byte(str), &res) 
    fmt.Println(err) 
    fmt.Println(res) 
} 

播放代码在https://play.golang.org/p/23ah8e_hCa

相关问题:Golang - Capitals in struct fields