-4

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)
}
jub0bs
  • 60,866
  • 25
  • 183
  • 186
gdk
  • 89
  • 1
  • 2
  • 11

1 Answers1

1

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:

  1. Set the content type header to application/json.
  2. Remove the 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}}'
 })
novalagung
  • 10,905
  • 4
  • 58
  • 82
  • nit-pick: the json tags are there, and your tags are incorrect (start with capital `N`). In your example, the JSON tags are actually not needed, default behaviour is to map JSON onto field names directly anyway – Elias Van Ootegem Nov 16 '18 at 11:44