douzhangbao2187 2017-07-04 00:58
浏览 55
已采纳

将json数组解组到go struct中(数组位于JSON字符串的中间

I am new to Go. I am working with a weather API. I have commented out the sections that cause the error. I have seen several other links that have a similar problem, however none of them seem to have the array in the middle of the JSON string. I'm sure there is a way to define the struct with a slice. I can't seem to get get the syntax to allow it. Here is where I'm stuck:

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
)

// WeatherData struct to collect data from the API call
type WeatherData struct {
    Wind Wind
    Sys  Sys
    // Weather Weather
    Name string `json:"name"`
}

////////////// ERROR when unmarshalling this struct /////////
// Weather provides basic weather info
// type Weather struct {
//  ID      int    `json:"id"`
//  Descrip string `json:"description"`
//  Icon    string `json:"icon"`
// }
/////////////////////////////////////////////////////////////

// Sys includes sunrise, sunset, country, etc.
type Sys struct {
    Country string `json:"country"`
}

// Wind struct to get specific wind characteristics
type Wind struct {
    Speed  float64 `json:"speed"`
    Degree float64 `json:"deg"`
    Gust   float64 `json:"gust"`
}

func main() {
    res, getErr := http.Get("http://api.openweathermap.org/data/2.5/weather?zip=REMOVED,us&appid=REMOVEDBUTWILLPOSTJSONData")
    if getErr != nil {
        log.Fatalln("http.Get error: ", getErr)
    }
    defer res.Body.Close()
    body, readErr := ioutil.ReadAll(res.Body)
    if readErr != nil {
        log.Fatalln("Read Error: ", readErr)
    }
//////////// UNABLE TO UNMARSHAL the array that passes through here ////
    var data WeatherData
    if err := json.Unmarshal(body, &data); err != nil {
        panic(err)
    }

    fmt.Println("Wind gusts: ", data.Wind.Gust)
    fmt.Println("Wind speed: ", data.Wind.Speed)
    fmt.Println("Wind degrees: ", data.Wind.Degree)

    fmt.Println("Country is: ", data.Sys.Country)
    fmt.Println("City is: ", data.Name)

///////////////// CAN'T ACCESS Description...or anything in Weather
// fmt.Println("Country is: ", data.Weather.Descrip) // cannot access due to this portion being inside an array

}



/////////////////THIS IS THE JSON DATA THAT IS AVAILABLE ///////////
{
  "coord": {
    "lon": -97.31,
    "lat": 32.94
  },
  "weather": [  // CAN'T ACCESS THIS CORRECTLY
    {
      "id": 800,
      "main": "Clear",
      "description": "clear sky",
      "icon": "01d"
    }
  ],
  "base": "stations",
  "main": {
    "temp": 306.46,
    "pressure": 1014,
    "humidity": 55,
    "temp_min": 306.15,
    "temp_max": 307.15
  },
  "visibility": 16093,
  "wind": {
    "speed": 5.1,
    "deg": 150,
    "gust": 7.2
  },
  "clouds": {
    "all": 1
  },
  "dt": 1499120100,
  "sys": {
    "type": 1,
    "id": 2597,
    "message": 0.0225,
    "country": "US",
    "sunrise": 1499081152,
    "sunset": 1499132486
  },
  "id": 0,
  "name": "Fort Worth",
  "cod": 200
}
  • 写回答

1条回答 默认 最新

  • douyun6781 2017-07-04 01:21
    关注

    You have to define slice of Weather struct in WeatherData.

    Uncomment Weather struct and update WeatherData struct to following.

    // WeatherData struct to collect data from the API call
    type WeatherData struct {
        Wind    Wind      `json:"wind"`
        Sys     Sys       `json:"sys"`
        Weather []Weather `json:"weather"`
        Name    string    `json:"name"`
    }
    

    Please have a look on example code: https://play.golang.org/p/4KFqRuxcx2

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?