URL解析JSON API为可读的文本在统一中/ c#



我正在尝试从API格式化JSON数据并存储结果。

数据由当地天气组成,提供基于当前时间的准确温度。

下面是我到目前为止所尝试的c#脚本:

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;
}

这是我的JSON数据:
{
"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
}
}

如有任何帮助,不胜感激。

你必须修复类

[Serializable]
public class jsonDataClass
{
public locationClass location;
public currentClass current;
}

[Serializable]
public class conditionClass
{
public string text ;
public string icon ;
public int code ;
}
[Serializable]
public class currentClass
{
public float temp_c;
public float temp_f;
public string last_updated;
public conditionClass condition;
}
// add all another fields starting from "wind_mph" to currentClass too

最新更新