/*WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW*\ ( ( ) ) |/ \| ) ) _((_ || (c) Wanzyee Studio < wanzyeestudio.blogspot.com > || ( ( |_ _ |=n |\ /| _____)) | ! ] U \.ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ./ (_(__(S) |___*/ using UnityEngine; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace WanzyeeStudio.Json{ /// /// Custom Newtonsoft.Json.JsonConverter for System.Collections.Generic.Dictionary. /// public class DictionaryConverter : JsonConverter{ /// /// Determine if the type is System.Collections.Generic.Dictionary. /// /// Type of the object. /// true if this can convert the specified type; otherwise, false. public override bool CanConvert(Type objectType){ if(!objectType.IsGenericType) return false; var _type = objectType.GetGenericTypeDefinition(); return typeof(Dictionary<,>) == _type || typeof(IDictionary<,>) == _type; } /// /// Read as System.Collections.Generic.KeyValuePair array to rebuild a dictionary. /// /// The object value. /// The Newtonsoft.Json.JsonReader to read from. /// Type of the object. /// The existing value of object being read. /// The calling serializer. public override object ReadJson( JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer ){ if(JsonToken.Null == reader.TokenType) return null; var _result = Activator.CreateInstance(objectType) as IDictionary; var _args = objectType.GetGenericArguments(); foreach(JObject _pair in JArray.Load(reader)){ var _key = _pair["Key"].ToObject(_args[0], serializer); var _value = _pair["Value"].ToObject(_args[1], serializer); if(!_result.Contains(_key)) _result.Add(_key, _value); else Debug.LogWarningFormat("Ignore pair with repeat key: {0}", _pair.ToString(Formatting.None)); } return _result; } /// /// Write as System.Collections.Generic.KeyValuePair array. /// /// The Newtonsoft.Json.JsonWriter to write to. /// The value. /// The calling serializer. public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer){ serializer.Serialize(writer, (value as IDictionary).Cast()); } } }