介绍
使用Unity自身的JsonUtility解析字典
- 字典类型实现接口ISerializationCallbackReceiver,相当于在转换之间进行键值对列表的分开解析
Json
{
"KeyList": [1, 2],
"ValueList": [{
"panelTypeString": "1",
"path": "q"
}, {
"panelTypeString": "2",
"path": "w"
}]
}
代码
using System;
using System.Collections.Generic;
using UnityEngine;
public class JsonLoad : MonoBehaviour
{
void Start()
{
LoadJson();
}
private void LoadJson()
{
string str = Resources.Load<TextAsset>("Json").text;
UIDataJson json = JsonUtility.FromJson<UIDataJson>(str);
Dictionary<int, UIData> dic = json.infodic;
foreach (var item in dic)
{
Debug.LogError(item.Key + ":" + item.Value);
}
}
}
[Serializable]
public class UIDataJson:ISerializationCallbackReceiver
{
public Dictionary<int, UIData> infodic;
public UIDataJson(Dictionary<int,UIData> data)
{
this.infodic = data;
}
//键值对解析
public List<int> KeyList = new List<int>();
public List<UIData> ValueList = new List<UIData>();
public void OnAfterDeserialize()
{
infodic = new Dictionary<int, UIData>();
for (int i = 0; i < Math.Min(KeyList.Count,ValueList.Count); i++)
{
infodic.Add(KeyList[i], ValueList[i]);
}
}
public void OnBeforeSerialize()
{
KeyList.Clear();
ValueList.Clear();
foreach (var item in infodic)
{
KeyList.Add(item.Key);
ValueList.Add(item.Value);
}
}
}
[Serializable]
public class UIData
{
public string panelTypeString;
public string path;
public UIData(string type, string path)
{
this.panelTypeString = type;
this.path = path;
}
}
网友评论