dongnigeng1295 2016-02-20 09:28
浏览 19
已采纳

在给定JSON结构的情况下表示Golang结构

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

... some more code ... then a part where I set the gin router context ... c ->>> *gin.Context

and then ...

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

gives me an output of:

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

How can I represent this structure properly or fix my code?

Or even better, an idea to get c.BindJSON(&uList) to work for Gin ...?

  • 写回答

1条回答 默认 最新

  • doushun9875 2016-02-20 09:50
    关注

    Your JSON is invalid if it is really equal to

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

    So your uList.URIs is empty. You could check for parsing error json.Unmarshal result.

    Proper JSON for your model should look like

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

    with struct like

    type URLs []string
    

    or

    {"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"`
    }
    

    Also you can replace json.Unmarshal([]byte(string(x)), &uList) with json.Unmarshal(x, &uList) as x is already []byte.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站