正如标题所说,我正在编写一个 API,采用客户端发布的任何 json 数据.
有没有办法直接获取像 bson.M
这样的map[string]interface{}
类型数据?
我尝试简单地查找gin.Context
的属性,如果我错过了什么,它们中的任何一个都会有所帮助吗?
- 直接从请求正文中获取
[]bytes
- 使用
json.Unmarshal()
将[]bytes
转换为类似 JSON 的数据:map[string]interface{}
func GetJsonData(c *gin.Context) {
data, _ := ioutil.ReadAll(c.Request.Body)
fmt.Println(string(data))
var jsonData bson.M // map[string]interface{}
data, _ := ioutil.ReadAll(c.Request.Body)
if e := json.Unmarshal(data, &jsonData); e != nil {
c.JSON(http.StatusBadRequest, gin.H{"msg": e.Error()})
return
}
c.JSON(http.StatusOK, jsonData)
}
您可以使用 JSON 解码器
type jsonPrametersMap map[string]interface{}
var m jsonPrametersMap
decoder := json.NewDecoder(bytes.NewReader(c.Request.Body))
if err := decoder.Decode(&m); err != nil {
fmt.Println(err)
return
}
游乐场在这里