You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

152 lines
6.4 KiB

  1. #region License
  2. // Copyright (c) 2007 James Newton-King
  3. //
  4. // Permission is hereby granted, free of charge, to any person
  5. // obtaining a copy of this software and associated documentation
  6. // files (the "Software"), to deal in the Software without
  7. // restriction, including without limitation the rights to use,
  8. // copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the
  10. // Software is furnished to do so, subject to the following
  11. // conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be
  14. // included in all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  17. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  18. // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  19. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  20. // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  21. // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  22. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  23. // OTHER DEALINGS IN THE SOFTWARE.
  24. #endregion
  25. using System;
  26. using System.Collections.Generic;
  27. using Newtonsoft.Json.Serialization;
  28. using Newtonsoft.Json.Utilities;
  29. using System.Reflection;
  30. namespace Newtonsoft.Json.Converters
  31. {
  32. /// <summary>
  33. /// Converts a <see cref="KeyValuePair{TKey,TValue}"/> to and from JSON.
  34. /// </summary>
  35. internal class KeyValuePairConverter : JsonConverter
  36. {
  37. private const string KeyName = "Key";
  38. private const string ValueName = "Value";
  39. private static readonly ThreadSafeStore<Type, ReflectionObject> ReflectionObjectPerType = new ThreadSafeStore<Type, ReflectionObject>(InitializeReflectionObject);
  40. private static ReflectionObject InitializeReflectionObject(Type t)
  41. {
  42. IList<Type> genericArguments = t.GetGenericArguments();
  43. Type keyType = genericArguments[0];
  44. Type valueType = genericArguments[1];
  45. return ReflectionObject.Create(t, t.GetConstructor(new[] { keyType, valueType }), KeyName, ValueName);
  46. }
  47. /// <summary>
  48. /// Writes the JSON representation of the object.
  49. /// </summary>
  50. /// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
  51. /// <param name="value">The value.</param>
  52. /// <param name="serializer">The calling serializer.</param>
  53. public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  54. {
  55. ReflectionObject reflectionObject = ReflectionObjectPerType.Get(value.GetType());
  56. DefaultContractResolver resolver = serializer.ContractResolver as DefaultContractResolver;
  57. writer.WriteStartObject();
  58. writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(KeyName) : KeyName);
  59. serializer.Serialize(writer, reflectionObject.GetValue(value, KeyName), reflectionObject.GetType(KeyName));
  60. writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(ValueName) : ValueName);
  61. serializer.Serialize(writer, reflectionObject.GetValue(value, ValueName), reflectionObject.GetType(ValueName));
  62. writer.WriteEndObject();
  63. }
  64. /// <summary>
  65. /// Reads the JSON representation of the object.
  66. /// </summary>
  67. /// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
  68. /// <param name="objectType">Type of the object.</param>
  69. /// <param name="existingValue">The existing value of object being read.</param>
  70. /// <param name="serializer">The calling serializer.</param>
  71. /// <returns>The object value.</returns>
  72. public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
  73. {
  74. if (reader.TokenType == JsonToken.Null)
  75. {
  76. if (!ReflectionUtils.IsNullableType(objectType))
  77. {
  78. throw JsonSerializationException.Create(reader, "Cannot convert null value to KeyValuePair.");
  79. }
  80. return null;
  81. }
  82. object key = null;
  83. object value = null;
  84. reader.ReadAndAssert();
  85. Type t = ReflectionUtils.IsNullableType(objectType)
  86. ? Nullable.GetUnderlyingType(objectType)
  87. : objectType;
  88. ReflectionObject reflectionObject = ReflectionObjectPerType.Get(t);
  89. JsonContract keyContract = serializer.ContractResolver.ResolveContract(reflectionObject.GetType(KeyName));
  90. JsonContract valueContract = serializer.ContractResolver.ResolveContract(reflectionObject.GetType(ValueName));
  91. while (reader.TokenType == JsonToken.PropertyName)
  92. {
  93. string propertyName = reader.Value.ToString();
  94. if (string.Equals(propertyName, KeyName, StringComparison.OrdinalIgnoreCase))
  95. {
  96. reader.ReadForTypeAndAssert(keyContract, false);
  97. key = serializer.Deserialize(reader, keyContract.UnderlyingType);
  98. }
  99. else if (string.Equals(propertyName, ValueName, StringComparison.OrdinalIgnoreCase))
  100. {
  101. reader.ReadForTypeAndAssert(valueContract, false);
  102. value = serializer.Deserialize(reader, valueContract.UnderlyingType);
  103. }
  104. else
  105. {
  106. reader.Skip();
  107. }
  108. reader.ReadAndAssert();
  109. }
  110. return reflectionObject.Creator(key, value);
  111. }
  112. /// <summary>
  113. /// Determines whether this instance can convert the specified object type.
  114. /// </summary>
  115. /// <param name="objectType">Type of the object.</param>
  116. /// <returns>
  117. /// <c>true</c> if this instance can convert the specified object type; otherwise, <c>false</c>.
  118. /// </returns>
  119. public override bool CanConvert(Type objectType)
  120. {
  121. Type t = (ReflectionUtils.IsNullableType(objectType))
  122. ? Nullable.GetUnderlyingType(objectType)
  123. : objectType;
  124. if (t.IsValueType() && t.IsGenericType())
  125. {
  126. return (t.GetGenericTypeDefinition() == typeof(KeyValuePair<,>));
  127. }
  128. return false;
  129. }
  130. }
  131. }