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.");
 }
相关推荐
木风小助理1 小时前
在 Spring Boot 中实现 JSON 字段的蛇形命
spring boot·后端·json
Hqst_xiangxuajun6 小时前
万兆SFP光纤笼子交换机和PCIE网卡主板上起到什么作用
网络·fpga开发·oracle·sqlite·json·信息与通信
38242782717 小时前
python:输出JSON
前端·python·json
就叫飞六吧20 小时前
JSONPath“隔空取物”思想,直击JSON深处的目标字段
服务器·windows·json
卓码软件测评1 天前
第三方软件测评机构:【Gatling构建JSON请求体StringBody、ElFileBody和Pebble模板的使用】
测试工具·性能优化·json·测试用例
爱敲点代码的小哥1 天前
json序列化和反序列化 和 数组转成json格式
java·前端·json
charlee441 天前
C++中JSON序列化和反序列化的实现
c++·json·序列化·结构体·nlohmann/json
救救孩子把1 天前
记录份Docker daemon.json配置-Docker镜像加速
docker·容器·json
博大世界1 天前
Matlab操作Json文件
json