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.");
 }
相关推荐
爱滑雪的码农13 小时前
Java基础二十:JSON 数据解析、对象与 JSON 互转逻辑
json
吴声子夜歌1 天前
PlantUML——显示JSON数据
json
祀爱1 天前
ControllerBase 类将对象转换为 JSON 格式并返回前端的方法
前端·json·asp.net
weelinking2 天前
【产品】11_实现后端接口——数据在背后如何流动
java·人工智能·python·sql·oracle·json·ai编程
油炸自行车2 天前
Claude Code 错误:API Error: 400 Failed to deserialize the JSON body into the
开发语言·javascript·json·trae·claude code·api error 400
NiceCloud喜云3 天前
Claude Code 跑 HyperFrames 实测:本地生成 AI 视频素材全流程
java·运维·人工智能·自动化·json·音视频·飞书
逍遥德3 天前
PostgreSQL --- JSON 函数详解
数据库·sql·postgresql·json
輕華3 天前
Flask_GET请求与JSON响应实战详解
python·flask·json
NiceCloud喜云3 天前
Claude Code Routines 实战:三种触发器跑通云端自动化编码
android·运维·数据库·人工智能·自动化·json·飞书
海兰4 天前
Kibana Dashboard as Code:Elastic 9.4 如何用 Terraform 和类型化 API 终结“JSON 垃圾袋“
云原生·json·terraform