I'm trying to format JSON data from an API and store the results.
The data consists of the local weather and provides accurate temperatures based on the current time.
Below is the C# script of what I've tried so far:
jsonDataController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class jsonDataController : MonoBehaviour
{
public string jsonURL = "http://api.weatherapi.com/v1/current.json?key=0ee485dfa1af4123a1a103953221107&q=London&aqi=no";
// Start is called before the first frame update
void Start()
{
StartCoroutine(generateData());
}
// Update is called once per frame
void Update()
{
}
IEnumerator generateData()
{
WWW www = new WWW(jsonURL);
yield return www;
if(www.error == null)
{
processJsonData(www.text)
}
}
protected void processJsonData(string url)
{
jsonDataClass jsonData = JsonUtility.FromJson<jsonDataClass>(url);
Debug.Log(jsonData.local);
Debug.Log(jsonData.current);
}
}
jsonDataClass.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[Serializable]
public class jsonDataClass
{
public string location;
public List<locationClass> local;
public List<currentClass> current;
}
[Serializable]
public class locationClass
{
public string name;
public string region;
public string country;
public float lat;
public float lon;
public string tz_id;
public int localtime_e;
public string localtime;
}
[Serializable]
public class currentClass
{
public float temp_c;
public float temp_f;
public string last_updated;
}
And this is my JSON data:
{
"location": {
"name": "London",
"region": "City of London, Greater London",
"country": "United Kingdom",
"lat": 51.52,
"lon": -0.11,
"tz_id": "Europe/London",
"localtime_epoch": 1657576622,
"localtime": "2022-07-11 22:57"
},
"current": {
"last_updated_epoch": 1657575900,
"last_updated": "2022-07-11 22:45",
"temp_c": 24,
"temp_f": 75.2,
"is_day": 0,
"condition": {
"text": "Clear",
"icon": "//cdn.weatherapi.com/weather/64x64/night/113.png",
"code": 1000
},
"wind_mph": 5.6,
"wind_kph": 9,
"wind_degree": 220,
"wind_dir": "SW",
"pressure_mb": 1023,
"pressure_in": 30.21,
"precip_mm": 0,
"precip_in": 0,
"humidity": 44,
"cloud": 0,
"feelslike_c": 24.8,
"feelslike_f": 76.6,
"vis_km": 10,
"vis_miles": 6,
"uv": 6,
"gust_mph": 6,
"gust_kph": 9.7
}
}
Any help would be appreciated.