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

Unity中如何访问API返回数组内的对象?JSON解析报错

解决Unity调用词典API时的"JSON must represent an object type"错误

你的推测完全正确,这个错误的核心原因是:目标API返回的JSON是顶层数组格式(外层由[]包裹,包含多个词条对象),但你当前使用JsonUtility.FromJson<Words>(json)直接尝试将其反序列化为单个Words对象,而Unity的JsonUtility默认不支持直接反序列化顶层数组,因此抛出该错误。

以下是具体的修复步骤:

1. 调整数据模型类

先把原来的Words类重命名为更清晰的WordEntry(避免和数组概念混淆),确保字段和API返回的结构匹配:

[System.Serializable]
public class WordEntry
{
    public string word;
    // 如果需要其他字段(比如音标、释义),可以在这里添加对应属性
}

2. 修改APIHelper处理数组

由于JsonUtility无法直接处理顶层数组,我们可以给返回的JSON字符串套一个对象外壳,用包装类来接收。修改后的APIHelper代码如下:

using UnityEngine;
using System.Net;
using System.IO;

public static class APIHelper
{
    public static WordEntry[] GetWordEntries()
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.dictionaryapi.dev/api/v2/entries/en/hello");
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        StreamReader reader = new StreamReader(response.GetResponseStream());
        string json = reader.ReadToEnd();
        
        // 给顶层数组套上对象外壳,让JsonUtility可以正常解析
        string wrappedJson = "{\"entries\":" + json + "}";
        WordList wordList = JsonUtility.FromJson<WordList>(wrappedJson);
        return wordList.entries;
    }
}

// 用于包装数组的辅助类,必须标记为可序列化
[System.Serializable]
public class WordList
{
    public WordEntry[] entries;
}

3. 更新MainScript的调用逻辑

现在API返回的是词条数组,我们需要从数组中取出目标元素(通常取第一个即可):

using TMPro;
using UnityEngine;

public class MainScript : MonoBehaviour
{
    public TextMeshProUGUI wordText;

    public void WriteWord()
    { 
        WordEntry[] entries = APIHelper.GetWordEntries();
        if (entries != null && entries.Length > 0)
        {
            wordText.text = entries[0].word;
        }
        else
        {
            wordText.text = "未查询到单词";
        }
    }
}

替代方案:使用自定义JsonHelper工具类

如果你不想手动套JSON外壳,可以用Unity官方推荐的JsonHelper工具类直接处理顶层数组:

public static class JsonHelper
{
    public static T[] FromJson<T>(string json)
    {
        Wrapper<T> wrapper = JsonUtility.FromJson<Wrapper<T>>("{\"Items\":" + json + "}");
        return wrapper.Items;
    }

    [System.Serializable]
    private class Wrapper<T>
    {
        public T[] Items;
    }
}

然后在APIHelper中替换反序列化逻辑:

public static WordEntry[] GetWordEntries()
{
    // ... 请求代码不变
    string json = reader.ReadToEnd();
    return JsonHelper.FromJson<WordEntry>(json);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 16:25:21