public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { Type dictType = value.GetType(); //Dictionary are marked as NonIntercept var dictGenericTypes = dictType.GetGenericArguments(); var keyType = dictGenericTypes[0]; var valueType = dictGenericTypes[1]; var serializerMethods = new SerializerMethods(writer, keyType, valueType); IObservableDictionaryEntries instanceEx = (IObservableDictionaryEntries)value; writer.WriteStartArray(); int caseType = instanceEx.CaseType; ValidateDictType(caseType); writer.WriteValue(caseType); var theDict = instanceEx.GetInternalDictionary(caseType); writer.WriteValue(theDict.Count); if (theDict.Count > 0) { writer.WriteStartObject(); foreach (var key in theDict.Keys) { serializerMethods.WriteKeyMethod(key); serializerMethods.WriteValueMethod(theDict[key]); } writer.WriteEndObject(); } writer.WriteEndArray(); }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.StartArray) { IObservableDictionaryEntries instanceEx = (IObservableDictionaryEntries)existingValue; reader.Read(); var dictType = (long)reader.Value; ValidateDictType(dictType); var dict = instanceEx.GetInternalDictionary((int)dictType); reader.Read(); var count = (long)reader.Value; if (count == 0) { return(instanceEx); } reader.Read();//To position reader.TokenType after count var types = objectType.GetGenericArguments(); var keyType = types[0]; var valueType = types[1]; var serializerMethods = new SerializerMethods(reader, keyType, valueType); try { instanceEx.DeltaTrackerNotifications(false); reader.Read();//We assume token at this point is StartToken and need to move past it while (reader.TokenType != JsonToken.EndObject) { object key = serializerMethods.ReadKeyMethod(); object value = serializerMethods.ReadValueMethod(); dict.Add(key, value); } return(instanceEx); } finally { instanceEx.DeltaTrackerNotifications(true); } } throw new NotImplementedException("Invalid Json format for Dictionary"); }