Unity3d使用JsonUtility.FromJson读取json文件

使用JsonUtility.FromJson方法不需要额外引用第三方库。该方法只能读取json对象,而不能读取json数组。

假如我们有如下的json数组:

复制代码
[
{"id":1, "name":"first2021", "level":5, "score":100, "isUser":false},
{"id":2, "name":"second2022", "level":5, "score":90, "isUser":false},
{"id":3, "name":"third2023", "level":5, "score":50, "isUser":false},
{"id":4, "name":"fourth2024", "level":5, "score":30, "isUser":true},
{"id":5, "name":"fifth2025", "level":5, "score":20, "isUser":false},
{"id":6, "name":"sixth2026", "level":5, "score":10, "isUser":false}
]

需要调整为:

复制代码
{"rankDatas":[
{"id":1, "name":"first2021", "level":5, "score":100, "isUser":false},
{"id":2, "name":"second2022", "level":5, "score":90, "isUser":false},
{"id":3, "name":"third2023", "level":5, "score":50, "isUser":false},
{"id":4, "name":"fourth2024", "level":5, "score":30, "isUser":true},
{"id":5, "name":"fifth2025", "level":5, "score":20, "isUser":false},
{"id":6, "name":"sixth2026", "level":5, "score":10, "isUser":false}
]}

我们将该文件放到Resources的json目录下,如下图所示:

我们创建RankData类存放反序列化之后的数据:

cs 复制代码
[System.Serializable]
public class RankData
{
    public int id;
    public string name;
    public int level;
    public int score;
    public bool isUser;
}

[System.Serializable]
public class RankDataList
{
    public RankData[] rankDatas;
}

其中RankDataList -> rankDatas的名字必须和json文件中最外层的key保持一致,否则会读取不到数据。

读取json文件并解析的逻辑如下:

cs 复制代码
 TextAsset jsonText = Resources.Load<TextAsset>("json/rank_info");
 if(jsonText != null)
 {
     string jsonData = jsonText.text;
     Debug.Log(jsonData);
     RankDataList rankDataList = JsonUtility.FromJson<RankDataList>(jsonData);

     foreach(var item in rankDataList.rankDatas)
     {
         Debug.Log("id:" + item.id);
     }
 }
 else
 {
     Debug.LogError("Can't find JSON file.");
 }
相关推荐
CSCN新手听安1 天前
【linux】网络基础(三)TCP服务端网络版本计算器的优化,Json的使用,服务器守护进程化daemon,重谈OSI七层模型
linux·服务器·网络·c++·tcp/ip·json
bloglin999991 天前
Qwen3-32B报错Invalid json output:{“type“: “1“}For troubleshooting, visit
llm·json
Trouvaille ~1 天前
【Linux】应用层协议设计实战(二):Jsoncpp序列化与完整实现
linux·运维·服务器·网络·c++·json·应用层
剩下了什么2 天前
MySQL JSON_SET() 函数
数据库·mysql·json
梦帮科技2 天前
Node.js配置生成器CLI工具开发实战
前端·人工智能·windows·前端框架·node.js·json
数据知道2 天前
PostgreSQL实战:详解如何用Python优雅地从PG中存取处理JSON
python·postgresql·json
缘空如是3 天前
基础工具包之JSON 工厂类
java·json·json切换
墨痕诉清风3 天前
CVS文件转Json格式
json·python3·cvs
数研小生3 天前
1688商品列表API:高效触达批发电商海量商品数据的技术方案
大数据·python·算法·信息可视化·json
devmoon3 天前
快速了解兼容 Ethereum 的 JSON-RPC 接口
开发语言·网络·rpc·json·区块链·智能合约·polkadot