unity通过天气接口获取json数据

首先先说一下我从中发现的需要的注意点,json接收的时候的类中的属性名一定要和json中的键值名字一样,否则的话接收不到,这个新手一定要谨记。

首先找一个天气接口的api,开始找网上的中国天气网的免费接口,但是获取到的数据不准确,后来找了个简单的,和风天气,申请简单也能免费用。所以目前用的和风的。https://www.heweather.com/

json原始数据:

{"HeWeather6":[{"basic":{"cid":"CN101090101","location":"石家庄","parent_city":"石家庄","admin_area":"河北","cnty":"中国","lat":"38.04547501","lon":"114.50246429","tz":"+8.0"},"update":{"loc":"2018-01-04 14:50","utc":"2018-01-04 06:50"},"status":"ok","now":{"cloud":"0","cond_code":"104","cond_txt":"阴","fl":"-6","hum":"32","pcpn":"0.0","pres":"1031","tmp":"0","vis":"8","wind_deg":"7","wind_dir":"北风","wind_sc":"微风","wind_spd":"5"}}]}

示例代码:

 /// <summary>
    /// 获取天气
    /// </summary>
    private void GetWeather()
    {
        StartCoroutine(IEGetWeather());
    }


    IEnumerator IEGetWeather()
    {
        if (WeatherURL != null)
        {
            WWW www = new WWW(WeatherURL);


            yield return new WaitUntil(() => www.isDone);




            WeatherInfo weather = JsonUtility.FromJson<WeatherInfo>(www.text);


            if (m_TempTxt != null)
            {
                m_TempTxt.text = weather.HeWeather6[0].now.tmp+" ℃";
            }


            if (m_WeatherIcon != null)
            {
                m_WeatherIcon.sprite = Resources.Load<Sprite>("Weather/" + weather.HeWeather6[0].now.cond_txt);
            }


            //Debug.Log(weather.weatherinfo.city);


        }
    }


    #region  天气Json




    [Serializable]
    public class WeatherInfo
    {


        public HeWeather6[] HeWeather6;
    }


    [Serializable]
    public class HeWeather6
    {
        public MBase basc;


        public MUpdate update;


        public string status;


        public MNow now;
    }


    [Serializable]
    public class MBase
    {
        public string cid;


        public string location;


        public string parent_city;


        public string admin_area;


        public string cnty;


        public string lat;


        public string lon;


        public string tz;
    }




    [Serializable]
    public class MUpdate
    {
        public string loc;


        public string utc;
    }


    [Serializable]
    public class MNow
    {
        public string cloud;


        public string cond_code;


        public string cond_txt;


        public string fl;


        public string hum;


        public string pcpn;


        public string pres;


        public string tmp;


        public string vis;


        public string wind_deg;


        public string wind_dir;


        public string wind_sc;


        public string wind_spd;
    }
    #endregion

猜你喜欢

转载自blog.csdn.net/qq_39353597/article/details/78971592