doufangpian5545 2018-11-16 09:02
浏览 415

如何在golang自定义结构类型中绑定json字符串化数据? [关闭]

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)
}
  • 写回答

1条回答 默认 最新

  • douxun2018 2018-11-16 09:59
    关注

    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}}'
     })
    
    评论

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP