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.");
 }
相关推荐
big狼王10 小时前
sqlserver存储过程中入参使用JSON
数据库·sqlserver·json
西京刀客12 小时前
Go语言json.Marshal多态机制
算法·golang·json
孜然卷k14 小时前
前端处理后端对象类型时间格式通用方法封装,前端JS处理JSON 序列化后的格式 java.time 包中的日期时间类
前端·json
kooboo china.2 天前
什么是JSON ?从核心语法到编辑器
javascript·编辑器·json
黑眼圈的小熊猫2 天前
项目-- Json-Rpc框架
rpc·json·php
大千AI助手2 天前
django中如何解析content-type=application/json的请求
django·sqlite·json
胡斌附体3 天前
接口获取到数组进行json对象转换
json·router·json.parse
python_chai3 天前
Django核心知识点全景解析
python·json
子正4 天前
C环境下更简洁的cJSON辅助函数
json