dtwkt46424 2019-03-23 03:28
浏览 195
已采纳

使用json.Unmarshal将http.Response转换为结构

I'm calling a remote API and getting a JSON response back. I'm trying to convert the *http.Response into a struct that I defined. Everything i've tried so far has resulted in an empty struct. Here is my attempt with json.Unmarshal

type Summary struct {
   Created  string  `json:"created"`          
   High     float64 `json:"high"`             
   Low      float64 `json:"low"`              
}

func getSummary() {

   url := "http://myurl"

   resp, err := http.Get(url)
   if err != nil {
       log.Fatalln(err)
   }

   body, err2 := ioutil.ReadAll(resp.Body)
   if err2 != nil {
       panic(err.Error())
   }

   log.Printf("body = %v", string(body))
   //outputs: {"success":true,"message":"","result":["High":0.43600000,"Low":0.43003737],"Created":"2017-06-25T03:06:46.83"}]}

   var summary = new(Summary)
   err3 := json.Unmarshal(body, &summary)
   if err3 != nil {
       fmt.Println("whoops:", err3)
       //outputs: whoops: <nil> 
   }

   log.Printf("s = %v", summary)
   //outputs: s = &{{0 0 0  0 0 0  0 0 0  0}}


}

What am I doing wrong? The JSON tags in my struct match the json keys from the response exactly...

edit: here is the JSON returned from the API

{
  "success": true,
  "message": "''",
  "result": [
    {
      "High": 0.0135,
      "Low": 0.012,
      "Created": "2014-02-13T00:00:00"
    }
  ]
}

edit i changed the struct to this but still not working

type Summary struct {
   Result struct {
       Created string  `json:"created"`
       High    float64 `json:"high"`
       Low     float64 `json:"low"`
   } 
 }
  • 写回答

2条回答 默认 最新

  • duanchun2349 2019-03-23 05:38
    关注

    Change your structure like this

    type Summary struct {
      Sucess bool `json:"success"`
      Message string `json:"message"`
      Result []Result `json:"result"`
    }
    
    type Result struct {
       Created string  `json:"Created"`
       High    float64 `json:"High"`
       Low     float64 `json:"Low"`
    } 
    

    Try this link

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

报告相同问题?

悬赏问题

  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制