dongzhuo3202 2014-08-24 18:57
浏览 49
已采纳

使用http.Request和Restangular在Go中查看JSON POST

I'm posting the following json string:

{'foods':[{'vName':'bean','color':'green','size':'small'}, 
           {'vName':'carrot','color':'orange', 'size':'medium'}]}

I'm posting to Go using Restangular, and the receiving func is:

func CreateFoods(w http.ResponseWriter, r *http.Request) {
   defer r.Body.Close()
   var food Food //this needs to be an array or something?
   dec := json.NewDecoder(r.Body)
   dec.Decode(&food)
}

My Food struct:

type Food struct{

  VName string `json:"vName"`
  Color string `json:"color"`
  Size string `json:"size"`
}

I've used this routine for cases where where I post a single entity, but now I want to post multiple entities, and I cannot figure out how to map this json example to multiple entities. Also, I'm trying to "see" the JSON POST, to see the JSON string, then if I have to, I can work with the string to make the entities. I cannot figure out how to get a hold of the JSON string from http.Request.

  • 写回答

2条回答 默认 最新

  • dsa99349 2014-08-24 19:12
    关注

    Add this:

    // You might use lowercase foods since it is maybe not something you want to export
    type Foods struct { 
      Foods []Food
    }
    

    When decoding use this:

    var foods Foods
    dec.Decode(&foods)
    

    To see the body of a response as a string:

    bytes, err := ioutil.ReadAll(r.Body)
    fmt.Println(string(bytes))
    

    Small detail: After the last two lines you now read the body contents. You should then decode the json not using json.NewDecoder and Decode but json.Unmarshal. Complete example for CreateFoods() to prevent confusion:

    bytes, err := ioutil.ReadAll(r.Body)
    if err != nil {
      fmt.Println("error reading body")
      return
    }
    fmt.Println(string(bytes))
    var foods Foods
    json.Unmarshal(bytes, &foods)
    

    Hope it works, didn't test, let me know!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 已有python代码,要求做成可执行程序,程序设计内容不多
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥15 小红薯封设备能解决的来
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答
  • ¥20 在本地部署CHATRWKV时遇到了AttributeError: 'str' object has no attribute 'requires_grad'
  • ¥15 vue+element项目中多tag时,切换Tab时iframe套第三方html页面需要实现不刷新
  • ¥50 深度强化学习解决能源调度问题