Unity自带Json解析库——JsonUtility
发布日期:2021-06-30 19:59:12
浏览次数:4
分类:技术文章
本文共 1935 字,大约阅读时间需要 6 分钟。
一:介绍
JsonUtility是Unity自带的一个类,简单,效率高,不依赖第三方的库,但是对于一些复杂的要求还是需要导入第三方库去实现
二:使用
{"personList":[{"Name":"liu","Age":1},{"Name":"Yin","Age":2}]}
using System.Collections.Generic;using UnityEngine;using System;public class ParseJson : MonoBehaviour{ private void Awake() { TextAsset json_txt = Resources.Load("TestJson"); PersonRoot data = JsonUtility.FromJson (json_txt.text); foreach (var temp in data.personList) { Debug.Log(String.Format("姓名:{0}==年龄{1}", temp.Name, temp.Age)); } }}[Serializable]public class PersonData{ public string Name; public int Age;}[Serializable]public class PersonRoot{ public List personList;}
三:踩坑点
——JsonUtility.FromJson方法只能接受一个JSON对象,否则会报错“JSON must represent an object type”
例如有多个对象时必须将多个对象定义为一个JSON对象——无法直接解析枚举类型
JsonUtility无法直接解析枚举类型,需要在JSON文件中定义与枚举类型相对应的字符串类型,之后在实体类中实现ISerializationCallbackReceiver接口将字符串转换为枚举类型using System.Collections.Generic;using UnityEngine;using System;public class ParseJson : MonoBehaviour{ private void Awake() { TextAsset json_txt = Resources.Load("TestJson"); PersonRoot data = JsonUtility.FromJson (json_txt.text); foreach (var temp in data.personList) { Debug.Log(String.Format("姓名:{0}==年龄{1}==类型{2}", temp.Name, temp.Age, temp.PersonType)); } }}[Serializable]public class PersonData : ISerializationCallbackReceiver{ public string Name; public int Age; public PersonType PersonType; public string PersonTypeStr; public void OnAfterDeserialize() { PersonType type = (PersonType)Enum.Parse(typeof(PersonType), PersonTypeStr); PersonType = type; } public void OnBeforeSerialize() { throw new NotImplementedException(); }}[Serializable]public class PersonRoot{ public List personList;}public enum PersonType{ Teacher, Student,}
转载地址:https://liuhaowen.blog.csdn.net/article/details/89437809 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
不错!
[***.144.177.141]2024年04月05日 21时26分08秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
【NLP学习笔记】中文分词(Word Segmentation,WS)
2021-07-03
【NLP学习笔记】词性标注(Part-of-speech Tagging, POS)
2021-07-03
【超越白皮书7】你需要知道关于ETH2.0的几个事实
2021-07-03
对于时间复杂度的通俗理解
2021-07-03
如何输入多组数据并输出每组数据的和?
2021-07-03
基于CentOS 7的Linux常用命令行命令
2021-07-03
行阶梯型矩阵
2021-07-03
matlab中uint8,double,im2double和im2uint8的区别
2021-07-03
SVM进行人脸检测
2021-07-03
C++学习笔记
2021-07-03
图像处理学习笔记
2021-07-03
Machine Learning Onramp on MATLAB 学习笔记
2021-07-03
Machine Learning with MATLAB 1.1 to 2.2
2021-07-03
Learning DSP with MATLAB
2021-07-03
用MATLAB实现m序列的生成(MATLAB 2021a适用)
2021-07-03
MATLAB函数备忘(定期更新)
2021-07-03
13行MATLAB代码实现网络爬虫 爬取NASA画廊星图
2021-07-03
MATLAB指定路径保存图片方法
2021-07-03
Python一键获取微信推送封面图
2021-07-03
油猴脚本:微信推送浏览功能拓展
2021-07-03