Unity自带Json解析库——JsonUtility
发布日期:2021-06-30 19:59:12 浏览次数:3 分类:技术文章

本文共 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 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:游戏UI框架——通过Json信息去加载UI面板
下一篇:Unity中实现解析Json文件

发表评论

最新留言

网站不错 人气很旺了 加油
[***.192.178.218]2024年04月29日 11时52分34秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章