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

Unity中JSON字符串数组解析失败求助:按教程操作仍报错

解决Unity中JSON数组解析失败的问题

问题详情

你尝试在Unity中解析根节点为数组的JSON,相关信息如下:

待解析的JSON数据

[
    {"id": 1, "name": "danny_devito", "img": "/images/1"},
    {"id": 2, "name": "jim_carey", "img": "/images/2"},
    {"id": 3, "name": "tyler_1", "img": "/images/3"}
]

定义的可序列化类

[System.Serializable]
public class Players {
    public int id;
    public string name;
    public string img;
}

[System.Serializable]
public class PlayersArray {
    public Players[] playersData;
}

解析代码

string playersJson = File.ReadAllText(Application.dataPath + "/playersFile.json");
PlayersArray loadedPlayerData = (PlayersArray)JsonUtility.FromJson<PlayersArray>(playersJson);

Debug.Log("Danny Boy: " + loadedPlayerData.playersData[0].name);

报错信息

解析报错

问题原因

Unity自带的JsonUtility不支持直接解析根节点为数组的JSON。你定义的PlayersArray类要求JSON根节点是一个包含playersData字段的对象,但实际JSON的根节点是数组,两者结构不匹配,导致解析失败。

修复方案

方案一:修改JSON结构(若允许)

将JSON调整为根节点是对象、包含playersData字段的格式,这样原解析代码可直接正常运行:

{
    "playersData": [
        {"id": 1, "name": "danny_devito", "img": "/images/1"},
        {"id": 2, "name": "jim_carey", "img": "/images/2"},
        {"id": 3, "name": "tyler_1", "img": "/images/3"}
    ]
}

方案二:不修改JSON的两种处理方式

1. 手动包装JSON字符串

在解析前给原JSON外层套上对象结构,适配PlayersArray类的格式:

string playersJson = File.ReadAllText(Application.dataPath + "/playersFile.json");
// 手动添加外层包装,将数组转为对象的playersData字段
string wrappedJson = "{\"playersData\":" + playersJson + "}";
PlayersArray loadedPlayerData = JsonUtility.FromJson<PlayersArray>(wrappedJson);
Debug.Log("Danny Boy: " + loadedPlayerData.playersData[0].name);

2. 使用第三方JSON库(推荐)

使用Newtonsoft.Json(Unity官方提供适配包),它支持直接解析根节点为数组的JSON,无需定义PlayersArray类:

using Newtonsoft.Json;

string playersJson = File.ReadAllText(Application.dataPath + "/playersFile.json");
Players[] loadedPlayers = JsonConvert.DeserializeObject<Players[]>(playersJson);
Debug.Log("Danny Boy: " + loadedPlayers[0].name);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 06:20:27