Home > Net >  Getting data from JSON array with Unity C#
Getting data from JSON array with Unity C#

Time:10-21

I am attempting to use the OpenWeatherMap API in unity C# with JSONUtility and I can't seem to access the "weather" array (specifically "main"), but I can access other information such as "timezone" and "name".

JSON file:

{
  "coord": {
    "lon": 10.99,
    "lat": 44.34
  },
  "weather": [
    {
      "id": 501,
      "main": "Rain",
      "description": "moderate rain",
      "icon": "10d"
    }
  ],
  "base": "stations",
  "main": {
    "temp": 298.48,
    "feels_like": 298.74,
    "temp_min": 297.56,
    "temp_max": 300.05,
    "pressure": 1015,
    "humidity": 64,
    "sea_level": 1015,
    "grnd_level": 933
  },
  "visibility": 10000,
  "wind": {
    "speed": 0.62,
    "deg": 349,
    "gust": 1.18
  },
  "rain": {
    "1h": 3.16
  },
  "clouds": {
    "all": 100
  },
  "dt": 1661870592,
  "sys": {
    "type": 2,
    "id": 2075663,
    "country": "IT",
    "sunrise": 1661834187,
    "sunset": 1661882248
  },
  "timezone": 7200,
  "id": 3163858,
  "name": "Zocca",
  "cod": 200
}  

 

In my C# script, I parse the data and I tried to make sure my variable types were accurate to the JSON file.

IEnumerator getWeatherInfo()
    {
        var www = new UnityWebRequest("https://api.openweathermap.org/data/2.5/weather?lat="   latitude   "&lon="   longitude   "&appid="   API_KEY)
        {
            downloadHandler = new DownloadHandlerBuffer()
        };

        yield return www.SendWebRequest();

        if (www.isNetworkError || www.isHttpError)
        {
            yield break;
        }

        Info = JsonUtility.FromJson<weatherInfo>(www.downloadHandler.text);
        var myData = Info.weather[0].id;

        Debug.Log(myData);
    }
}

[SerializeField]
public class weatherInfo
{
    public Weather[] weather;
    public float timezone;
    public float id;
    public string name;
    public int cod;
}

[SerializeField]
public class Weather
{
    public int id;
    public string main;
    public string description;
    public string icon;
}

However, the error I get is NullReferenceException when this line is executed:

var myData = Info.weather[0].id;

CodePudding user response:

The [SerializeField] attribute is a Unity specific attribute to serialise, and then usually display, private fields.

Force Unity to serialize a private field.

When Unity serializes your scripts, it only serializes public fields. If you also want Unity to serialize your private fields you can add the SerializeField attribute to those fields. (link).

What's you need to decorate your classes with is [Serializable]. i.e.:

[Serializable]
public class weatherInfo
{
    public Weather[] weather;
    public float timezone;
    public float id;
    public string name;
    public int cod;
}
  • Related