1、Json文本需要是List类型的,定义的枚举类型的字段必须和Json文本中的一致
{
"infoList":
[
{
"panelTypeString": "Task",
"path": "UIPanel/TaskPanel"
},
{
"panelTypeString": "Knapsack",
"path": "UIPanel/KnapsackPanel"
},
{
"panelTypeString": "Skill",
"path": "UIPanel/SkillPanel"
},
{
"panelTypeString": "Shop",
"path": "UIPanel/ShopPanel"
},
{
"panelTypeString": "ItemMessage",
"path": "UIPanel/ItemMessagePanel"
},
{
"panelTypeString": "System",
"path": "UIPanel/SystemPanel"
},
{
"panelTypeString": "MainMenu",
"path": "UIPanel/MainMenuPanel"
}
]
}
2、需要用对象解析,应定义一个类,类中有和Json文本中的List对应的属性
[Serializable]
class UIPanelTypeJson
{
public List<UIPanelInfo> infoList;
}
3、定义和Json文本相对应的实体类
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
[Serializable]
public class UIPanelInfo : ISerializationCallbackReceiver {
[NonSerialized]
public UIPanelType panelType;
public string panelTypeString;
public string path;
//反序列化 从文本信息 到对象
public void OnAfterDeserialize()
{
UIPanelType type = (UIPanelType)System.Enum.Parse(typeof(UIPanelType), panelTypeString);
panelType = type;
}
public void OnBeforeSerialize()
{
}
}
4、解析Json文本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class Resolver
{
private Dictionary<UIPanelType, string> panelPathDict;
private Resolver()
{
ParsePanelTypeJosn();
}
[Serializable]
class UIPanelTypeJson
{
public List<UIPanelInfo> infoList;
}
/// <summary>
/// 解析Json
/// </summary>
private void ParsePanelTypeJosn()
{
panelPathDict = new Dictionary<UIPanelType, string>();
TextAsset textAsset = Resources.Load<TextAsset>("UIPanelInfo");
UIPanelTypeJson jsonObject = JsonUtility.FromJson<UIPanelTypeJson>(textAsset.text);
foreach (UIPanelInfo info in jsonObject.infoList)
{
panelPathDict.Add(info.panelType, info.path);
}
}
/// <summary>
/// 测试方法
/// </summary>
public void Test()
{
string path;
panelPathDict.TryGetValue(UIPanelType.Knapsack, out path);
Debug.Log(path);
}
}