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
相关产品推荐
相关产品推荐

