本文主要是介绍Unity jsonUtility序列化ListT,DictionaryT等泛型,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
原文地址 https://blog.csdn.net/Truck_Truck/article/details/78292390
// Serialization.cs
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;// List<T>
[Serializable]
public class Serialization<T>
{[SerializeField]List<T> target;public List<T> ToList() { return target; }public Serialization(List<T> target){this.target = target;}
}// Dictionary<TKey, TValue>
[Serializable]
public class Serialization<TKey, TValue> : ISerializationCallbackReceiver
{[SerializeField]List<TKey> keys;[SerializeField]List<TValue> values;Dictionary<TKey, TValue> target;public Dictionary<TKey, TValue> ToDictionary() { return target; }public Serialization(Dictionary<TKey, TValue> target){this.target = target;}public void OnBeforeSerialize(){keys = new List<TKey>(target.Keys);values = new List<TValue>(target.Values);}public void OnAfterDeserialize(){var count = Math.Min(keys.Count, values.Count);target = new Dictionary<TKey, TValue>(count);for (var i = 0; i < count; ++i){target.Add(keys[i], values[i]);}}
}
在这个思路的基础上封装了两个方法出来更方便使用
public class SerializeTools
{public static string ListToJson<T>(List<T> l) {return JsonUtility.ToJson(new Serialization<T>(l));}public static List<T> ListFromJson<T>(string str) {return JsonUtility.FromJson<Serialization<T>>(str).ToList();}public static string DicToJson<TKey, TValue>(Dictionary<TKey, TValue> dic){return JsonUtility.ToJson(new Serialization<TKey, TValue>(dic));}public static Dictionary<TKey, TValue> DicFromJson<TKey, TValue>(string str){return JsonUtility.FromJson<Serialization<TKey, TValue>>(str).ToDictionary();}}
这篇关于Unity jsonUtility序列化ListT,DictionaryT等泛型的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!