Reputation: 1118
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\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] )
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 ...?
Upvotes: 0
Views: 109
Reputation: 4235
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
.
Upvotes: 1