1

I am writing a C# script in unity to get the weather of the location the player is in. I am almost done, all I have to do is extract the data from the JSON file the weather API returned. I am using SimpleJSON to read and extract the JSON. The JSON looks something like this:

{
  "coord": {
    "lon": (floating point number),
    "lat": (floating point number)
  },
  "weather": [
    {
      "id": 804,
      "main": "Clouds",
      "description": "overcast clouds",
      "icon": "04n"
    }
  ],
  "base": "stations",
  "main": {
    "temp": 292.01,
    "feels_like": 292.12,
    "temp_min": 291.15,
    "temp_max": 293.15,
    "pressure": 1018,
    "humidity": 72
  },
  "visibility": 9000,
  "wind": {
    "speed": 1.5,
    "deg": 130
  },
  "clouds": {
    "all": 100
  },
  "dt": 1594239812,
  "sys": {
    "type": 1,
    "id": 1308,
    "country": "COUNTRY-CODE",
    "sunrise": 1594178675,
    "sunset": 1594235893
  },
  "timezone": 7200,
  "id": 2954172,
  "name": "CITY",
  "cod": 200
}

I need to access the "description" in the "weather" array. However I could not figure out how to get it to work. This is my C# code:

var PARSED_JSON_2 = JSON.Parse(JSON_DATA_2);
var weather_description = PARSED_JSON_2["weather"][2]; //returns null
//I also tried something like this:
var weather_description = PARSED_JSON_2["weather"]["description"][2]; //returns null
var weather_description = PARSED_JSON_2["weather"]["description"][2].Value; //Returns nothing.

A Debug.Log would show an empty string.

I tried to follow this reference here: http://wiki.unity3d.com/index.php/SimpleJSON

(In a nutshell I need to access an element inside of a JSON array, but I can't figure out how to. Any help is appreciated.)

10
  • 1
    needs to be done with SimpleJSON? or could you use any other third party library? Commented Jul 9, 2020 at 12:45
  • 1
    I am on linux, so my options aren't as abundant. I found SimpleJSON to work best up until this point, but if you have suggestion, I would try it aswell. As long as I can figure out how to access the element "description" inside the "weather" array of the json file. Commented Jul 9, 2020 at 12:46
  • 2
    you can create C# Class and deserialize it to C# object. You can update field as per your wish Commented Jul 9, 2020 at 12:48
  • 1
    I'll suggest to use Newtonsoft (I don't know if it works on linux or not), or you can use my JsonManager (github.com/EricBatlle/SimpleUnityUtils/tree/master/Assets/…) Commented Jul 9, 2020 at 12:48
  • 1
    @Lotan is it cross platform / does it work with unity? I am aiming to make this cross platform, mainly targeting mobile devices. Oh, lol. I take that back - Just saw the using UnityEngine; Commented Jul 9, 2020 at 12:51

1 Answer 1

4

You are trying to access an index 2 that does not exist. There is only one single element in the weather array. In this case that SimpleJSON library simply returns null instead of throwing a proper exception!

You should rather use the index 0

var weather_description = PARSED_JSON_2["weather"][0];

In general you could also use the JsonUtility and deserialize your complete array into a proper c# class representation. Then you would immediately see how many elements the array/s has/have or get the expected exceptions properly.

Yours would look like

[Serializable]
public class Root
{
    public Coord coord;
    public Weather[] weather;
    public string @base;
    public Main main;
    public int visibility;
    public Wind wind;
    public Clouds clouds;
    public double dt;
    public Sys sys;
    public int timezone;
    public int id;
    public string name;
    public int cod;
}

[Serializable]
public class Coord
{
    public float lon;
    public float lat;
}

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

[Serializable]
public class Main
{
    public float temp;
    public float feels_like;
    public float temp_min;
    public float temp_max;
    public float pressure;
    public float humidity;
}

[Serializable]
public class Wind
{
    public float speed;
    public float deg;
}

[Serializable]
public class Clouds
{
    public int all;
}

[Serializable]
public class Sys
{
    public int type;
    public int id;
    public string country;
    public int sunrise;
    public int sunset;
}

And then you would do e.g.

var root = JsonUtility.FromJson<Root>(JSON_DATA_2);
var weather = root.weather[0];

The big advantage of this approach would be that you can also directly see the result in the Inspector of Unity by writing into a

public class JsonTester : MonoBehaviour
{
    [Header("Input")]
    [Tooltip("Copy your json string here and call \"Test\" from the Context menu")]
    [SerializeField] [TextArea] private string _testJson;

    [Header("Output")]
    [SerializeField] private Root _receivedJson;

    [ContextMenu(nameof(Test))]
    private void Test()
    {
        VisualizeJson(_testJson);
    }

    public void VisualizeJson(string json)
        JsonUtility.FromJsonOverwrite(json, _receivedJson);
    }
}

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.