2 using System.Collections.Generic;
5 using Newtonsoft.Json.Utilities;
6 using System.Reflection;
8 namespace Newtonsoft.Json.Converters
11 /// Converts a <see cref="KeyValuePair{TKey,TValue}"/> to and from JSON.
13 public class KeyValuePairConverter : JsonConverter
16 /// Writes the JSON representation of the object.
18 /// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
19 /// <param name="value">The value.</param>
20 /// <param name="serializer">The calling serializer.</param>
21 public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
23 Type t = value.GetType();
24 PropertyInfo keyProperty = t.GetProperty("Key");
25 PropertyInfo valueProperty = t.GetProperty("Value");
27 writer.WriteStartObject();
28 writer.WritePropertyName("Key");
29 serializer.Serialize(writer, ReflectionUtils.GetMemberValue(keyProperty, value));
30 writer.WritePropertyName("Value");
31 serializer.Serialize(writer, ReflectionUtils.GetMemberValue(valueProperty, value));
32 writer.WriteEndObject();
36 /// Reads the JSON representation of the object.
38 /// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
39 /// <param name="objectType">Type of the object.</param>
40 /// <param name="existingValue">The existing value of object being read.</param>
41 /// <param name="serializer">The calling serializer.</param>
42 /// <returns>The object value.</returns>
43 public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
45 IList<Type> genericArguments = objectType.GetGenericArguments();
46 Type keyType = genericArguments[0];
47 Type valueType = genericArguments[1];
51 object key = serializer.Deserialize(reader, keyType);
54 object value = serializer.Deserialize(reader, valueType);
57 return ReflectionUtils.CreateInstance(objectType, key, value);
61 /// Determines whether this instance can convert the specified object type.
63 /// <param name="objectType">Type of the object.</param>
65 /// <c>true</c> if this instance can convert the specified object type; otherwise, <c>false</c>.
67 public override bool CanConvert(Type objectType)
69 if (objectType.IsValueType && objectType.IsGenericType)
70 return (objectType.GetGenericTypeDefinition() == typeof (KeyValuePair<,>));