给定一个JSON结构的Golang结构

时间:2016-02-20 09:28:19

标签: json go

type requestNodeType struct {
// edited: added the last part
    urls    []string  `json:"urls"` 
}

...更多代码......然后是我设置gin路由器上下文的一部分...... c - >>> * gin.Context

然后......

x, _ := ioutil.ReadAll(c.Request.Body)
fmt.Printf("crb2 = %s\n", string(x))
uList := requestNodeType{}
json.Unmarshal(x, &uList)
// edited: updated prints for clarity 
fmt.Printf("json1 = %+v, %T - %p\n", uList, uList, uList )
fmt.Printf("json2 = %+v, %T - %p\n", uList.urls, uList.urls, uList.urls )
fmt.Printf("json3 = %+v, %T - %p\n", uList.urls[0], uList.urls[0], uList.urls[0] )

给我输出:

crb2 = {"urls":["http://www.indeed.com/viewjob?jk=9388f66529358f6a", "http://www.indeed.com/viewjob?jk=53e937ef73c0c808"]}
json1 = {urls:[]}, main.requestNodeType - %!p(main.requestNodeType={[]})
json2 = [], []string - 0x0
2016/02/20 09:10:39 Panic recovery -> runtime error: index out of range

如何正确表示此结构或修复我的代码?

或者甚至更好,让c.BindJSON(& uList)为Gin工作的想法......?

1 个答案:

答案 0 :(得分:1)

如果JSON确实等于

,则JSON无效
{["http://www.jobs.com/job?jk=9388f66529358f6a","http://www.job.com/job?jk=53e937ef73c0c808"]}

所以你的uList.URIs是空的。您可以检查解析错误json.Unmarshal结果。

您的模型的正确JSON应该看起来像

["http://www.jobs.com/job?jk=9388f66529358f6a","http://www.job.com/job?jk=53e937ef73c0c808"]

with struct like

type URLs []string

{"URLs": ["http://www.jobs.com/job?jk=9388f66529358f6a","http://www.job.com/job?jk=53e937ef73c0c808"]}

with struct like

type requestNodeType struct {
    URLs []string `json:"URLs"`
}

此外,您可以将json.Unmarshal([]byte(string(x)), &uList)替换为json.Unmarshal(x, &uList),因为x已经[]byte