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条)

报告相同问题?

悬赏问题

  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题