Using JSONObject to get data from a weather api

Hi all,

I usually find an answer on here or by googling, but am stumped - it does not help that I have never used JSON before. I’m trying to bring in one value from Weather API - OpenWeatherMap and use it to determine what Sprite is shown:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SkyIoT : MonoBehaviour {

//the sprites
    public Sprite img1 , img2;


    IEnumerator AdjustSkyToWeather() {
        while (true) {
//the particular URL from where I want to get this data
            string weatherUrl = "http://api.openweathermap.org/data/2.5/forecast?id=6167863&appid={api_key}";

            WWW weatherWWW = new WWW (weatherUrl);
            yield return weatherWWW;

            JSONObject tempData = new JSONObject (weatherWWW.text);
//get the data as a JSON Object and then get the first value of Main
            JSONObject weatherDetails = tempData["weather"];
            string WeatherType = weatherDetails[0]["main"].str;

//determining which sprite to use
            if (WeatherType == "Clear") {
                gameObject.GetComponent<SpriteRenderer>().sprite = img1;
                Debug.Log ("Clear");
            } else if (WeatherType == "Clouds" || WeatherType == "Rain" || WeatherType == "Snow") {
                gameObject.GetComponent<SpriteRenderer>().sprite = img2;
                Debug.Log ("Cloudy");
            }
//checking for new data ever ten minutes
            yield return new WaitForSeconds(600);
        }
    }

    void Start () {
        StartCoroutine (AdjustSkyToWeather());
    }
}

But I’m getting this error:
"
NullReferenceException: Object reference not set to an instance of an object
SkyIoT+c__Iterator0.MoveNext () (at Assets/SkyIoT.cs:21)
UnityEngine.SetupCoroutine.InvokeMoveNext (IEnumerator enumerator, IntPtr returnValueAddress) (at /Users/builduser/buildslave/unity/build/Runtime/Export/Coroutines.cs:17)
"

Which refers to this line of code:

string WeatherType = weatherDetails[0] ["main"].str;

As far as I understand it, that should get the first value that comes after “main”?

I modified the original code from this site: Web APIs and the IoT in Unity — SitePoint

Any help would be greatly appreciated!

I had the same errors for a while. There’s a new way to do this in Unity. While my code only does the temperature, it might be useful to you if you’re still interested (I know it’s been over three years!)

Let me know, and I’ll paste it.

If you could post it that would be great