unity含枚举类型json数据的序列化和反序列化

♀尐吖头ヾ 提交于 2020-01-14 15:46:10

unity含枚举类型json数据的序列化

编程环境win10+unity5.3f+VS2017

unity的json功能不支持枚举类型的数据,这里写一下刚学到的转化方式。

建立一个枚举类

public enum UIPanelType  {
    ItemMessage,
    Knapsack,
    MainMenu,
    Shop,
    Skill,
    System,
    Task
}

主要思想是利用String存储枚举类型,并且在每次生成对象时把String转换为枚举类型。

using UnityEngine;
using System.Collections;
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);
        //数据转化把string类型转化为枚举类型
        panelType = type;
    }

    public void OnBeforeSerialize()//这个方法在每次序列化前调用
    {
        
    }
}

把json数据取出来存到字典里面。

  private void ParseUIPanelTypeJson()
    {
        panelPathDict = new Dictionary<UIPanelType, string>();

        TextAsset ta = Resources.Load<TextAsset>("UIPanelType");

        UIPanelTypeJson jsonObject = JsonUtility.FromJson<UIPanelTypeJson>(ta.text);

        foreach (UIPanelInfo info in jsonObject.infoList) 
        {
            //Debug.Log(info.panelType);
            panelPathDict.Add(info.panelType, info.path);
        }
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!