You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity/C#解析API返回JSON数据并格式化存储问题求助

解决Unity中WeatherAPI JSON数据解析问题

问题根源

你的代码无法正确解析JSON的核心原因是数据模型类与API返回的JSON结构不匹配,同时使用了已过时的网络请求API,导致数据无法正常映射。

修正后的代码

jsonDataClass.cs(数据模型类)

using UnityEngine;

[Serializable]
public class jsonDataClass
{
    // 与JSON中的"location"对象一一对应,不再使用List或错误的string类型
    public locationClass location; 
    // 与JSON中的"current"对象一一对应,不再使用List
    public 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;
    // 修正字段名,匹配JSON中的"localtime_epoch"
    public int localtime_epoch;
    public string localtime;
}

[Serializable]
public class currentClass
{
    public float temp_c;
    public float temp_f;
    public string last_updated;
    // 若需要解析更多字段(如condition、wind等),可在此添加对应属性
}

jsonDataController.cs(请求与解析逻辑)

using System.Collections;
using UnityEngine;
using UnityEngine.Networking;

public class jsonDataController : MonoBehaviour
{
    public string jsonURL = "http://api.weatherapi.com/v1/current.json?key=0ee485dfa1af4123a1a103953221107&q=London&aqi=no";

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

    IEnumerator FetchWeatherData()
    {
        // 使用Unity推荐的UnityWebRequest替代已弃用的WWW类
        using (UnityWebRequest webRequest = UnityWebRequest.Get(jsonURL))
        {
            yield return webRequest.SendWebRequest();

            if (webRequest.result != UnityWebRequest.Result.Success)
            {
                Debug.LogError($"请求失败: {webRequest.error}");
            }
            else
            {
                ProcessJsonData(webRequest.downloadHandler.text);
            }
        }
    }

    protected void ProcessJsonData(string jsonText)
    {
        jsonDataClass jsonData = JsonUtility.FromJson<jsonDataClass>(jsonText);
        
        // 打印具体字段值,而非直接打印对象引用
        if (jsonData.location != null)
        {
            Debug.Log($"城市: {jsonData.location.name}, 地区: {jsonData.location.region}");
            Debug.Log($"当地时间: {jsonData.location.localtime}");
        }
        
        if (jsonData.current != null)
        {
            Debug.Log($"实时温度(摄氏度): {jsonData.current.temp_c}°C");
            Debug.Log($"实时温度(华氏度): {jsonData.current.temp_f}°F");
            Debug.Log($"最后更新时间: {jsonData.current.last_updated}");
        }
    }
}

关键说明

  1. 结构匹配:JSON中的location和current都是单个对象,而非数组,因此模型类中不能用List<T>,需直接声明对应类的字段。
  2. 字段名一致:模型类的字段名必须与JSON中的键完全匹配(大小写敏感),比如localtime_epoch不能简写为localtime_e。
  3. 网络请求升级:Unity已弃用WWW类,改用UnityWebRequest更稳定,且using语句可自动释放资源,避免内存泄漏。
  4. 调试优化:直接打印对象会输出引用地址,需打印具体字段才能看到实际解析的数据。

内容的提问来源于stack exchange,提问作者Pepwave Dave

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 06:57:15