How to bind json stringify data in golang custom struct type?
js ajax
$.ajax({
type: "POST"
, url : url
, data : JSON.stringify('{"nowBlockPositionX":3,"nowBlockPositionY":0,"nowBlock":{"O":0}}')
})
go custom struct
type demo struct {
nowBlockPositionX int `form:"nowBlockPositionX" json:"nowBlockPositionX"`
NowBlockPositionY int `form:"nowBlockPositionY" json:"nowBlockPositionY"`
NowBlock map[string]int `form:"nowBlock" json:"nowBlock" query:"nowBlock"`
}
don't binding this
demo := new(demo)
if err := c.Bind(demo); err != nil {
c.Logger().Error(err)
}
First, fix the demo
struct. The field in the struct need to be exported. Just change the first character of each field to be in uppercase.
Then remove the form:
and query:
tags. You only need the json:
tag.
type demo struct {
NowBlockPositionX int `json:"NowBlockPositionX"`
NowBlockPositionY int `json:"NowBlockPositionY"`
NowBlock map[string]int `json:"NowBlock"`
}
There are also few problems appear on your javascript code, on the $.ajax
statement.
Do this two things:
application/json
.JSON.stringify()
since your data already in string.Working code:
$.ajax({
url : url,
type: "POST",
dataType: "json",
contentType: "application/json",
data: '{"nowBlockPositionX":3,"nowBlockPositionY":0,"nowBlock":{"O":0}}'
})