本文共 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/