Unity读取json的工具类JsonUtility

首先我们需要定义我们的json文件,我们可以在Resources文件夹下面创建一个.json的文件,写上如下内容

{
"infoList":
[
{"panelTypeString":"ItemMessage",
"path":"UIPanel/ItemMessagePanel"},

{"panelTypeString":"Knapsack",
"path":"UIPanel/KnapsackPanel"},

{"panelTypeString":"MainMenu",
"path":"UIPanel/MainMenuPanel"},

{"panelTypeString":"Shop",
"path":"UIPanel/ShopPanel"},

{"panelTypeString":"Skill",
"path":"UIPanel/SkillPanel"},

{"panelTypeString":"System",
"path":"UIPanel/SystemPanel"},

{"panelTypeString":"Task",
"path":"UIPanel/TaskPanel"}

]
}

内置的json类虽然方便但是也有缺陷,不能用于读取文本内容,我们使用的时候必须转换为对象读取,本章我们本来是想使用枚举来定义panelTypeString的值的,但是发现这个方法对于枚举并不友好,所以进行了一下改进

创建一个PanelInfo的脚本,用来存放我们的json内容。

[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()
    {

    }
}

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

注意使用序列化Serializable的时候需要引用system这个命名空间
对于枚举我们需要单独声明不需要序列化,否则编译不能执行,因为序列化不支持枚举所以我们在UIPanelType 前面打上NonSerialized标签。

解析完成后下面我们就可以对这个数据进行读取了
创建一个UIManager类

  /// 单例模式的核心
    /// 1,定义一个静态的对象 在外界访问 在内部构造
    /// 2,构造方法私有化

    private static UIManager _instance;

    public static UIManager Instance
    {
        get
        {
            if (_instance == null)
            {
                _instance = new UIManager();
            }
            return _instance;
        }
    }
    ///构造函数
    private UIManager()
    {
        ParseUIPanelTypeJson();
    }

    private Dictionary<UIPanelType, string> panelPathDict;//存储所有面板Prefab的路径

    ///序列化json对象(必须有)
    [Serializable]
    class UIPanelTypeJson
    {
        public List<UIPanelInfo> infoList;
    }
    ///读取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);
        }
    }

    /// <summary>
    /// just for test
    /// </summary>
    public void Test()
    {
        string path ;
        panelPathDict.TryGetValue(UIPanelType.Knapsack,out path);
        Debug.Log(path);
    }

这样通过调用我们的测试方法就可以看到文件里面的内容了,如果内容没有错误就说明解析完成了

pass:功能单一,胜在轻便小巧,限制有点多。

猜你喜欢

转载自blog.csdn.net/qq_41056203/article/details/80722248