【发布时间】:2018-11-21 16:47:39
【问题描述】:
我的问题是, 如何在地图对象(变量)中绑定(自动绑定?)自定义结构类型?
这是我的自定义结构类型
type Tetris struct {
... ...
NowBlock map[string]int `form:"nowBlock" json:"nowBlock"`
... ...
}
这是我的 ajax 代码
$.ajax({
type : "POST"
, url : "/game/tetris/api/control"
, data : {
"keyCode" : keyCode
, "ctxWidth" : ctxWidth
, "ctxHeight" : ctxHeight
, "nowBlock" : {"O":0}
} // also, i did JSON.stringify, but did not binding..
, dataType : "json"
, contentType : "application/json"
}).done(function(data){
... ...
});
然后,不要绑定“NowBlock”
tetris := new(Tetris)
if err := c.Bind(tetris); err != nil {
c.Logger().Error(err)
}
fmt.Println(tetris.NowBlock)
println 结果是,
'map[]' //nil...
这是我的完整问题链接(GOLANG > How to bind ajax json data to custom struct type?)
请帮帮我。
附言。谢谢你回答我。
我确实喜欢这个答案。
但是,它也不起作用。
首先,
- No 'contentType : "application/json"'
- don't use JSON.stringify
then, in go side,
- fmt.println(tetris.KeyCode) // OK
- fmt.println(tetris.NowBlock) // NOT OK.. 'map[]'
第二,
- Use 'contentType : "application/json"'
- Use JSON.stringify
then, in go side,
- fmt.println(tetris.KeyCode) // NOT OK.. '' (nil)
- fmt.println(tetris.NowBlock) // NOT OK.. 'map[]'
第三,
i remove the custom struct type Tetris NowBlock object's `form:nowBlock` literal,
but is does not working too...
为什么不在地图对象中绑定自定义结构类型?
我很抱歉。我解决了这个问题。
问题是我的自定义结构类型有另一个自定义结构类型。
像这样。
type Tetris struct {
Common Common
NowBlock map[string]int `json:"nowBlock"`
}
type Common struct {
CtxWidth int `json:"ctxWidth"`
CtxHeight int `json:"ctxHeight"`
KeyCode int `form:"keyCode" json:"keyCode"`
}
在这种情况下,我做到了
$.ajax({
type : "POST"
, url : "/game/tetris/api/control"
, data : {
"keyCode" : keyCode
, "ctxWidth" : ctxWidth
, "ctxHeight" : ctxHeight
, "nowBlock" : {"O":0}
} // also, i did JSON.stringify, but did not binding..
, dataType : "json"
, contentType : "application/json"
}).done(function(data){
... ...
});
但是,这是错误的! 正确的是,
$.ajax({
type : "POST"
, url : "/game/tetris/api/control"
, data : JSON.stringify({
"Common" : {
"keyCode" : keyCode
, "ctxWidth" : ctxWidth
, "ctxHeight" : ctxHeight
}
, "nowBlock" : {"O":0}
})
, dataType : "json"
, contentType : "application/json"
}).done(function(data){
... ...
在json数据中,'Common' struct type的数据必须有“Common” 'Key:value' map...
我很高兴收到您的回答和关注。
【问题讨论】:
-
我们可以知道
c是什么吗? -
对不起。 'c' 是上下文。(回显框架链接 > echo.labstack.com/guide/request)
标签: json go data-binding go-echo