JsonUtility解析Json

JsonUtility解析Json


JsonUtility是Unity官方的一个解析Json的API,下面是我定义的Json文件,记录了项目中的panle预制件名字和与其所在的路径。

{
  "infoList": 
  [
    {
      "panelTypeString": "MainMenu",
      "path": "UIPanel/MainMenuPanel"
    },
    {
      "panelTypeString": "Task",
      "path": "UIPanel/TaskPanel"
    },
    {
      "panelTypeString": "Knapsack",
      "path": "UIPanel/KnapsackPanel"
    },
    {
      "panelTypeString": "Skill",
      "path": "UIPanel/SkillPanel"
    },
    {
      "panelTypeString": "Battle",
      "path": "UIPanel/BattlePanel"
    },
    {
      "panelTypeString": "System",
      "path": "UIPanel/SystemPanel"
    },
    {
      "panelTypeString": "KnapsackPop",
      "path": "UIPanel/KnapsackPopPanel"
    }
  ]
}

为了从json文件里面获取到相关的信息,需要做以下准备,代码如下:

using UnityEngine;
using System;

/// 
/// panel 信息类
/// 
/// 注意这里需要加这个可序列化属性 [Serializable],不然解析会报错
[Serializable]
public class PanelInfo:ISerializationCallbackReceiver {
    [NonSerialized]
    public UIPanelType panelType;
    public string panelTypeString;
    //{
    //    get { return panelType.ToString(); }
    //    set
    //    {
    //       UIPanelType type=(UIPanelType) System.Enum.Parse(typeof(UIPanelType), value);
    //        panelType = type;
    //    }
    //}
    public string path;

    public void OnBeforeSerialize()
    {

    }
    //反序列化=>从文本信息到对象
    public void OnAfterDeserialize()
    {
        UIPanelType type = (UIPanelType)System.Enum.Parse(typeof(UIPanelType),panelTypeString);
        panelType = type;
    }
}

 /// 
    /// 对应json文件里面的数组
    /// 
    ///  [Serializable] 属性不可缺,不然会报错
    [Serializable]
    class UIPanelTypeJson
    {
        public List infoList;
    }

    /// 
    /// 解析json文件过程
    /// 
    private void UIPanelPathParson()
    {
        panelPathDict = new Dictionarystring>();
        TextAsset uiPanelType = Resources.Load("UIPanelType");
        UIPanelTypeJson panelTypeJson= JsonUtility.FromJson(uiPanelType.text);

        foreach (PanelInfo panelInfo in panelTypeJson.infoList)
        {
            Debug.Log(panelInfo.path);
        }
    }

你可能感兴趣的:(JsonUtility解析Json)