public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { bool isdictionary = typeof(IDictionary).IsAssignableFrom(objectType); CustomContractResolver resolver = (CustomContractResolver)serializer.ContractResolver; resolver.Skip = true; if (isdictionary && reader.TokenType != JsonToken.StartObject) { IDictionary result = (IDictionary)System.Activator.CreateInstance(objectType); Type[] arguments = result.GetType().GetGenericArguments(); Type keyType = arguments[0]; Type valueType = arguments[1]; var listedType = typeof(List <>).MakeGenericType(valueType); // This will loop in itself badly... IEnumerable temp = (IEnumerable)serializer.Deserialize(reader, listedType); int pos = 0; foreach (var o in temp) { // We "might" be able to get the keys from the ID's themselves // to provide backwards compatibility... string key = this.setOrGetIdValue(pos.ToString(), o); if (result.Contains(key)) { throw new Exception("CE: Error while converting array to associative map. Possible duplicated ID's in array definition."); } result.Add(key, o); pos++; } return(result); } else { // This will loop in itself badly... IDictionary result = (IDictionary)serializer.Deserialize(reader, objectType); // Now populate ID's with keys when possible... foreach (string key in result.Keys) { this.setOrGetIdValue(key, result[key], true); } return(result); } throw new Exception("CE: Unsupported operation."); }
/// <summary> /// Deserializes from JSON converting all JARRAYS to associative /// arrays... /// </summary> /// <typeparam name="TType"></typeparam> /// <param name="value"></param> /// <returns></returns> public static object DeserializeObject(string value, Type targetType) { using (var strReader = new StringReader(value)) { using (var jsonReader = new CustomJsonTextReader(strReader)) { var resolver = new CustomContractResolver(); var serializer = new CustomJsonSerializer { ContractResolver = resolver, ObjectCreationHandling = ObjectCreationHandling.Replace }; object unserialized = serializer.Deserialize(jsonReader, targetType); return(unserialized); } } }