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

Unity中用C#结合SimpleJSON读取JSON数组内description字段问题

解决SimpleJSON访问天气API数组内字段的问题

嘿,我一眼就看出你踩坑的地方了!咱们一步步把这个问题搞定:

首先看你给出的JSON结构,weather是一个数组(注意外面的方括号[]),而且里面只有1个对象元素。你之前的错误主要集中在两个点:数组索引用错了,还有字段访问的层级逻辑不对。

你的错误写法分析

  • PARSED_JSON_2["weather"][2]:数组索引是从0开始的,你的weather数组里只有1个元素,最大索引是0,用[2]肯定越界返回null
  • PARSED_JSON_2["weather"]["description"][2]:weather是数组,不是直接的对象,不能直接通过["description"]访问,得先拿到数组里的具体对象,再去取它的字段

正确的访问方式

用SimpleJSON先访问数组元素,再访问对象字段就可以了,代码如下:

var parsedJson = JSON.Parse(JSON_DATA_2);
// 先获取weather数组,取第一个元素(索引0),再提取description字段
string weatherDescription = parsedJson["weather"][0]["description"].Value;
Debug.Log(weatherDescription); // 会输出"overcast clouds"

额外的安全处理(避免空引用报错)

为了防止API返回的数组为空或者字段缺失,建议加个判断逻辑,让代码更健壮:

var parsedJson = JSON.Parse(JSON_DATA_2);
// 先检查weather数组是否存在且不为空
if (parsedJson["weather"] != null && parsedJson["weather"].Count > 0)
{
    var weatherObj = parsedJson["weather"][0];
    // 再检查description字段是否存在
    if (weatherObj.HasKey("description"))
    {
        string weatherDescription = weatherObj["description"].Value;
        Debug.Log(weatherDescription);
    }
    else
    {
        Debug.Log("未找到description字段");
    }
}
else
{
    Debug.Log("天气数据数组为空");
}

这样就能稳稳拿到你想要的天气描述啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 12:57:46