ISerializationCallbackReceiver接口的使用(用于解析JSON文本)

来源:互联网 发布:scala与java的不同 编辑:程序博客网 时间:2024/06/08 06:21

最近学习UI框架中,需要解析JSON文本

{"infoList":[{"panelType": "MainMenuPanel","path": "UIPanel/MainMenuPanel"},{"panelType": "TaskPanel","path": "UIPanel/TaskPanel"},{"panelType": "KnapsackPanel","path": "UIPanel/KnapsackPanel"},{"panelType": "BattlePanel","path": "UIPanel/BattlePanel"},{"panelType": "SkillPanel","path": "UIPanel/SkillPanel"},{"panelType": "ShopPanel","path": "UIPanel/ShopPanel"},{"panelType": "SystemPanel","path": "UIPanel/SystemPanel"}]}

[Serializable]public class UIPanelInfo{    public UIPanelType panelType;    public string path;}[Serializable]public class UIPanelInfoJson{    public List<UIPanelInfo> infoList;}
其中,path为string类型,而panelType为Enum类型,使用JsonUtility进行解析时报错(我觉得应该是没有成功解析枚举类型)。


经过查找一些文档后,发现了一个挺好用的接口ISerializationCallbackReceiver,实现这个接口后有两个方法,一个是反序列化后,一个是序列化前

[Serializable]public class UIPanelInfo:ISerializationCallbackReceiver{    public UIPanelType panelType;    public string path;    public void OnAfterDeserialize()    {        throw new NotImplementedException();    }    public void OnBeforeSerialize()    {        throw new NotImplementedException();    }}[Serializable]public class UIPanelInfoJson{    public List<UIPanelInfo> infoList;}
对枚举类型UIPanelType进行修改,增加一个string类型,进行两种之前的转换

[Serializable]public class UIPanelInfo:ISerializationCallbackReceiver{    [NonSerialized]    public UIPanelType panelType;    public string path;    public string panelTypeString;    public void OnAfterDeserialize()    {        UIPanelType type = (UIPanelType) Enum.Parse(typeof(UIPanelType), panelTypeString);        panelType = type;    }    public void OnBeforeSerialize()    {    }}[Serializable]public class UIPanelInfoJson{    public List<UIPanelInfo> infoList;}

用这种方法,可以成功解析JSON文本。

注:如果有某些错误,希望各路大神们批评指正