107 lines
2.4 KiB
C#
107 lines
2.4 KiB
C#
/************************
|
|
* Json工具相关类 *
|
|
************************/
|
|
using UnityEngine;
|
|
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using System;
|
|
|
|
#region
|
|
/// <summary>
|
|
/// 封装的可序列化列表对象
|
|
/// </summary>
|
|
[Serializable]
|
|
public class Serialization<T>
|
|
{
|
|
[SerializeField]
|
|
List<T> target;
|
|
public List<T> ToList() { return target; }
|
|
|
|
public Serialization(List<T> target)
|
|
{
|
|
this.target = target;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 封装的可序列化字典对象
|
|
/// </summary>
|
|
[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]);
|
|
}
|
|
}
|
|
}
|
|
#endregion
|
|
|
|
/// <summary>
|
|
/// JSON数据工具
|
|
/// </summary>
|
|
public class JsonTools
|
|
{
|
|
/// <summary>
|
|
/// 列表对象转JSON字符串
|
|
/// </summary>
|
|
public static string ListToJson<T>(List<T> l)
|
|
{
|
|
return JsonUtility.ToJson(new Serialization<T>(l));
|
|
}
|
|
|
|
/// <summary>
|
|
/// JSON字符串转列表对象
|
|
/// </summary>
|
|
public static List<T> ListFromJson<T>(string str)
|
|
{
|
|
return JsonUtility.FromJson<Serialization<T>>(str).ToList();
|
|
}
|
|
|
|
/// <summary>
|
|
/// 字典对象转JSON字符串
|
|
/// </summary>
|
|
public static string DicToJson<TKey, TValue>(Dictionary<TKey, TValue> dic)
|
|
{
|
|
return JsonUtility.ToJson(new Serialization<TKey, TValue>(dic));
|
|
}
|
|
|
|
/// <summary>
|
|
/// JSON字符串转字典对象
|
|
/// </summary>
|
|
public static Dictionary<TKey, TValue> DicFromJson<TKey, TValue>(string str)
|
|
{
|
|
return JsonUtility.FromJson<Serialization<TKey, TValue>>(str).ToDictionary();
|
|
}
|
|
|
|
/// <summary>
|
|
/// JSON字符串转对象
|
|
/// </summary>
|
|
public static T ObjectFromJson<T>(string str)
|
|
{
|
|
return JsonUtility.FromJson<T>(str);
|
|
}
|
|
}
|
|
|