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.");
 }
相关推荐
inxunoffice2 小时前
批量修改记事本文本文件编码,可以解决文本文件乱码问题
json
Kaede69 小时前
怎么安装JSON服务器?JSON服务器最新安装教程
运维·服务器·json
还是鼠鼠15 小时前
Node.js Express 处理静态资源
前端·javascript·vscode·node.js·json·express
witton18 小时前
MinGW下编译ffmpeg源码时生成compile_commands.json
ffmpeg·json·makefile·mingw·调试·compile_command·remake
Ronin-Lotus1 天前
嵌入式硬件篇---JSON通信以及解析
python·嵌入式硬件·json
百锦再1 天前
React编程的核心概念:发布-订阅模型、背压与异步非阻塞
前端·javascript·react.js·前端框架·json·ecmascript·html5
DA02212 天前
C++轻量HeaderOnly的JSON库
开发语言·c++·json
树下一少年2 天前
docker-compose部署prometheus+grafana+node_exporter
docker·json·grafana·prometheus·node_exporter
JhonKI3 天前
【从零实现Json-Rpc框架】- 项目实现 - Dispatcher模块实现篇
qt·rpc·json
Python测试之道3 天前
Deepseek API+Python 测试用例一键生成与导出 V1.0.5(支持读取json及yml文件,虚拟环境及库安装指导保姆级指南)
python·json·测试用例