2016-12-28 96 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