博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Unity自带Json解析库——JsonUtility
阅读量:1986 次
发布时间:2019-04-27

本文共 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,}

转载地址:http://wxyvf.baihongyu.com/

你可能感兴趣的文章
CodeForces - 931B World Cup (思维 模拟)
查看>>
ACM 2017 北京区域赛 J-Pangu and Stones(区间dp)
查看>>
HDU - 5643 King's Game (约瑟夫环变式)
查看>>
UVA - 1452 Jump (约瑟夫环变式)
查看>>
POJ - 3517 And Then There Was One (约瑟夫环变式)
查看>>
HDU - 2068 RPG的错排 (错排+组合数)
查看>>
CodeForces 591C Median Smoothing(思维 模拟)
查看>>
Spring Cloud Spring Boot b2b2c 微服务 多商家入驻直播商城之Maven 项目模板
查看>>
mac || Linux 命令行下实现批量重命名
查看>>
java常用类 String面试题
查看>>
Windows10下的powershell美化教程
查看>>
利用ffmpeg合并音频和视频
查看>>
刷好老毛子系统进不了老毛子系统后台的解决办法
查看>>
Parallels Desktop 16 不能联网的解决办法
查看>>
ERROR 1292 (22007): Incorrect datetime value: ‘2002‘ for column ‘出版日期‘ at row 1
查看>>
SLAM中TUM数据集更改图片名字
查看>>
手把手教你--jquery chosen插件的使用和API(html下拉框美化)
查看>>
手把手教你--jsp读取配置文件(properties文件)--(JSTL的fmt:setBundle和fmt:message读取properties文件)
查看>>
手把手教你--JAVA微信支付(H5支付)
查看>>
solr修改schema文件(solr修改配置文件)
查看>>