123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105 |
- #if !COMBAT_SERVER
- using System;
- using System.Collections.Generic;
- using UnityEngine;
- namespace Fort23.GameData
- {
- public class JsonHelper
- {
- public static string ToJson(object obj)
- {
- #if !COMBAT_SERVER
- return JsonUtility.ToJson(obj);
- #endif
- return null;
- }
- public static T FromJson<T>(string json)
- {
- #if !COMBAT_SERVER
- return JsonUtility.FromJson<T>(json);
- #endif
- return default;
- }
- public static object FromJson(string json, Type type)
- {
- #if !COMBAT_SERVER
- return JsonUtility.FromJson(json, type);
- #endif
- return null;
- }
- public static T Clone<T>(T t)
- {
- return FromJson<T>(ToJson(t));
- }
- }
- /// <summary>
- /// 扩展JsonUtility的List能力, T必须加上[Serializable]标签
- /// https://blog.csdn.net/Truck_Truck/article/details/78292390
- /// </summary>
- /// <typeparam name="T"></typeparam>
- [Serializable]
- public class Serialization<T>
- {
- [SerializeField] List<T> target;
- public List<T> ToList()
- {
- return target;
- }
- public Serialization(List<T> target)
- {
- this.target = target;
- }
- }
- /// <summary>
- /// 扩展JsonUtility的Dictionary能力,TValue必须加上[Serializable]标签
- /// Dictionary<TKey, TValue>
- /// </summary>
- /// <typeparam name="TKey"></typeparam>
- /// <typeparam name="TValue"></typeparam>
- [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]);
- }
- }
- }
- }
- #endif
|