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.

155 lines
6.2 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. #if !NET20
  26. using System;
  27. using Newtonsoft.Json.Serialization;
  28. using System.Globalization;
  29. using Newtonsoft.Json.Utilities;
  30. namespace Newtonsoft.Json.Converters
  31. {
  32. /// <summary>
  33. /// Converts an Entity Framework <see cref="T:System.Data.EntityKeyMember"/> to and from JSON.
  34. /// </summary>
  35. internal class EntityKeyMemberConverter : JsonConverter
  36. {
  37. private const string EntityKeyMemberFullTypeName = "System.Data.EntityKeyMember";
  38. private const string KeyPropertyName = "Key";
  39. private const string TypePropertyName = "Type";
  40. private const string ValuePropertyName = "Value";
  41. private static ReflectionObject _reflectionObject;
  42. /// <summary>
  43. /// Writes the JSON representation of the object.
  44. /// </summary>
  45. /// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
  46. /// <param name="value">The value.</param>
  47. /// <param name="serializer">The calling serializer.</param>
  48. public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  49. {
  50. EnsureReflectionObject(value.GetType());
  51. DefaultContractResolver resolver = serializer.ContractResolver as DefaultContractResolver;
  52. string keyName = (string)_reflectionObject.GetValue(value, KeyPropertyName);
  53. object keyValue = _reflectionObject.GetValue(value, ValuePropertyName);
  54. Type keyValueType = keyValue?.GetType();
  55. writer.WriteStartObject();
  56. writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(KeyPropertyName) : KeyPropertyName);
  57. writer.WriteValue(keyName);
  58. writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(TypePropertyName) : TypePropertyName);
  59. writer.WriteValue(keyValueType?.FullName);
  60. writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(ValuePropertyName) : ValuePropertyName);
  61. if (keyValueType != null)
  62. {
  63. if (JsonSerializerInternalWriter.TryConvertToString(keyValue, keyValueType, out string valueJson))
  64. {
  65. writer.WriteValue(valueJson);
  66. }
  67. else
  68. {
  69. writer.WriteValue(keyValue);
  70. }
  71. }
  72. else
  73. {
  74. writer.WriteNull();
  75. }
  76. writer.WriteEndObject();
  77. }
  78. private static void ReadAndAssertProperty(JsonReader reader, string propertyName)
  79. {
  80. reader.ReadAndAssert();
  81. if (reader.TokenType != JsonToken.PropertyName || !string.Equals(reader.Value.ToString(), propertyName, StringComparison.OrdinalIgnoreCase))
  82. {
  83. throw new JsonSerializationException("Expected JSON property '{0}'.".FormatWith(CultureInfo.InvariantCulture, propertyName));
  84. }
  85. }
  86. /// <summary>
  87. /// Reads the JSON representation of the object.
  88. /// </summary>
  89. /// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
  90. /// <param name="objectType">Type of the object.</param>
  91. /// <param name="existingValue">The existing value of object being read.</param>
  92. /// <param name="serializer">The calling serializer.</param>
  93. /// <returns>The object value.</returns>
  94. public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
  95. {
  96. EnsureReflectionObject(objectType);
  97. object entityKeyMember = _reflectionObject.Creator();
  98. ReadAndAssertProperty(reader, KeyPropertyName);
  99. reader.ReadAndAssert();
  100. _reflectionObject.SetValue(entityKeyMember, KeyPropertyName, reader.Value.ToString());
  101. ReadAndAssertProperty(reader, TypePropertyName);
  102. reader.ReadAndAssert();
  103. string type = reader.Value.ToString();
  104. Type t = Type.GetType(type);
  105. ReadAndAssertProperty(reader, ValuePropertyName);
  106. reader.ReadAndAssert();
  107. _reflectionObject.SetValue(entityKeyMember, ValuePropertyName, serializer.Deserialize(reader, t));
  108. reader.ReadAndAssert();
  109. return entityKeyMember;
  110. }
  111. private static void EnsureReflectionObject(Type objectType)
  112. {
  113. if (_reflectionObject == null)
  114. {
  115. _reflectionObject = ReflectionObject.Create(objectType, KeyPropertyName, ValuePropertyName);
  116. }
  117. }
  118. /// <summary>
  119. /// Determines whether this instance can convert the specified object type.
  120. /// </summary>
  121. /// <param name="objectType">Type of the object.</param>
  122. /// <returns>
  123. /// <c>true</c> if this instance can convert the specified object type; otherwise, <c>false</c>.
  124. /// </returns>
  125. public override bool CanConvert(Type objectType)
  126. {
  127. return objectType.AssignableToTypeName(EntityKeyMemberFullTypeName, false);
  128. }
  129. }
  130. }
  131. #endif