正如标题所述,我正在编写一个API,获取客户端发布的任何json数据。有没有办法直接得到bson.M这样的map[string]interface{}类型的数据?我试着简单地查找gin.Context的属性,如果我错过了什么,它们中的任何一个都能帮助我吗?
bson.M
map[string]interface{}
gin.Context
nhaq1z211#
1.直接从请求主体获取[]bytes1.使用json.Unmarshal()将[]bytes转换为类似JSON的数据:map[string]interface{}
[]bytes
json.Unmarshal()
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) }
eit6fx6z2#
你可以使用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 }
Playground
2条答案
按热度按时间nhaq1z211#
1.直接从请求主体获取
[]bytes
1.使用
json.Unmarshal()
将[]bytes
转换为类似JSON的数据:map[string]interface{}
eit6fx6z2#
你可以使用json解码器
Playground