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

Unity C#中用JSONUtility解析OpenWeatherMap API的weather数组报错

解决Unity JsonUtility解析OpenWeatherMap API返回的weather数组空引用问题

问题原因

触发NullReferenceException的核心原因是Unity的JsonUtility无法识别未正确标记可序列化的类。你给weatherInfo和Weather类添加的[SerializeField]属性仅用于让私有字段在Unity编辑器中序列化,而非标记整个类为可序列化类型,导致JsonUtility无法解析JSON中的数组结构,最终Info.weather为null。

修正步骤

1. 修正类的序列化标记

将类上的[SerializeField]替换为[System.Serializable],让JsonUtility能识别这些类并正确解析数组:

using System; // 引入命名空间简化属性写法

[Serializable]
public class weatherInfo
{
    public Weather[] weather;
    public float timezone;
    public int id; // 修正类型:JSON中id是整数,改为int更匹配
    public string name;
    public int cod;
}

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

2. 添加空值检查(推荐)

在访问数组元素前增加有效性判断,避免再次触发空引用异常:

Info = JsonUtility.FromJson<weatherInfo>(www.downloadHandler.text);

// 先确认weather数组有效再访问
if (Info.weather != null && Info.weather.Length > 0)
{
    var myData = Info.weather[0].id;
    Debug.Log(myData);
    Debug.Log("天气类型:" + Info.weather[0].main);
}
else
{
    Debug.LogWarning("未获取到有效天气信息数组");
}

3. 优化请求状态判断(可选)

UnityWebRequest的isNetworkError和isHttpError已被弃用,建议改用result属性判断请求状态:

yield return www.SendWebRequest();

if (www.result != UnityWebRequest.Result.Success)
{
    Debug.LogError(www.error);
    yield break;
}

验证效果

修正后,JsonUtility就能正确解析返回JSON中的weather数组,你可以正常访问其中的id、main等字段。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 20:10:29