dtwkt46424
dtwkt46424
2019-03-23 03:28

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

  • IT行业问题
  • 计算机技术
  • it技术
  • 编程语言问答
  • 互联网问答
已采纳

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 duanchun2349 2年前

    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

    点赞 评论 复制链接分享
  • duanmei1922 duanmei1922 2年前

    Its because you're trying to unmarshal an array into struct, Use array instead of the Result struct

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

    Use this weblink to convert your JSON objects to Go Struct >> https://mholt.github.io/json-to-go/

    点赞 评论 复制链接分享