golang, revel, How to parse post json?

huangapple go评论69阅读模式
英文:

golang, revel, How to parse post json?

问题

我在golang方面还比较新,但我正在努力学习。

我正在尝试通过POST请求将JSON发送到revel控制器,并在revel端解析它。

但是在获取结果时,我无法进行解组(Unmarshal)...我正在发送一个数组

json_encode(array("one","two","three"))

但是我找不到正确的方法来处理这样的数据。我不确定在发送之前是否需要生成JSON。

func (c KpiCtrl) GetData() revel.Result {
    content, _ := ioutil.ReadAll(c.Request.Body)
    ...
    return c.RenderJson(content)
}

返回的结果是

"WyJvbmUiLCJ0d28iLCJ0aHJlZSJd"

我尝试使用json.Unmarshal,但是它返回错误。在使用curl发送给revel控制器的POST数据方面,有什么最佳实践吗?

英文:

I'm rather new in golang, but I'm trying hard..

I'm trying to send json by post request to the revel controller, and parse it on the revel side.

But while getting the result I cannot Unmarshal it... I'm sending an array

json_encode(array("one","two","three"))

But I can't find the correct way to work with such a data. I'm not sure do I need to make json before sending it or not..

func (c KpiCtrl) GetData() revel.Result {
    content, _ := ioutil.ReadAll(c.Request.Body)
    ...
    return c.RenderJson(content)
}

returns

"WyJvbmUiLCJ0d28iLCJ0aHJlZSJd"

I tried to use json.Unmarshal but it returns errors.. What is the best practice to work with post data sent by curl to revel controller?

答案1

得分: 4

只需使用标准的json解码器:

var content []string
err := json.NewDecoder(c.Request.Body).Decode(&content)
if err != nil {
    log.Fatal("JSON解码错误:", err)
}
defer c.Request.Body.Close()
fmt.Println(content)
英文:

Just use standart json Decoder:

   var content []string
   err := json.NewDecoder(c.Request.Body).Decode(&content)
   if err != nil {
	   log.Fatal("JSON decode error: ", err)
   }
   defer c.Request.Body.Close()
   fmt.Println(content)

huangapple
  • 本文由 发表于 2016年2月8日 22:46:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/35272392.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定