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

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();

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

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

        foreach (UIPanelInfo info in jsonObject.infoList) 
        {
            //Debug.Log(info.panelType);
            panelPathDict.Add(info.panelType, info.path);
        }
    }

你可能感兴趣的:(c#,unity3d)