0

我正在调用远程 API 并返回 JSON 响应。我正在尝试将其转换*http.Response为我定义的结构。到目前为止我尝试过的一切都导致了一个空结构。这是我对 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}}


}

我究竟做错了什么?我的结构中的 JSON 标签与响应中的 json 键完全匹配......

编辑:这是从 API 返回的 JSON

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

编辑 我将结构更改为此但仍然无法正常工作

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

2 回答 2

2

像这样改变你的结构

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"`
} 

试试这个链接

于 2019-03-23T05:38:37.667 回答
0

这是因为您试图将数组解组为结构,使用数组而不是 Result 结构

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

使用此网络链接将您的 JSON 对象转换为 Go Struct >> https://mholt.github.io/json-to-go/

于 2019-03-23T05:45:29.573 回答