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.

184 lines
7.1 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 System.Globalization;
  28. using System.Reflection;
  29. using System.Runtime.Serialization;
  30. using Newtonsoft.Json.Utilities;
  31. #if NET20
  32. using Newtonsoft.Json.Utilities.LinqBridge;
  33. #else
  34. using System.Linq;
  35. #endif
  36. namespace Newtonsoft.Json.Converters
  37. {
  38. /// <summary>
  39. /// Converts an <see cref="Enum"/> to and from its name string value.
  40. /// </summary>
  41. internal class StringEnumConverter : JsonConverter
  42. {
  43. /// <summary>
  44. /// Gets or sets a value indicating whether the written enum text should be camel case.
  45. /// The default value is <c>false</c>.
  46. /// </summary>
  47. /// <value><c>true</c> if the written enum text will be camel case; otherwise, <c>false</c>.</value>
  48. public bool CamelCaseText { get; set; }
  49. /// <summary>
  50. /// Gets or sets a value indicating whether integer values are allowed when deserializing.
  51. /// The default value is <c>true</c>.
  52. /// </summary>
  53. /// <value><c>true</c> if integers are allowed when deserializing; otherwise, <c>false</c>.</value>
  54. public bool AllowIntegerValues { get; set; }
  55. /// <summary>
  56. /// Initializes a new instance of the <see cref="StringEnumConverter"/> class.
  57. /// </summary>
  58. public StringEnumConverter()
  59. {
  60. AllowIntegerValues = true;
  61. }
  62. /// <summary>
  63. /// Initializes a new instance of the <see cref="StringEnumConverter"/> class.
  64. /// </summary>
  65. /// <param name="camelCaseText"><c>true</c> if the written enum text will be camel case; otherwise, <c>false</c>.</param>
  66. public StringEnumConverter(bool camelCaseText)
  67. : this()
  68. {
  69. CamelCaseText = camelCaseText;
  70. }
  71. /// <summary>
  72. /// Writes the JSON representation of the object.
  73. /// </summary>
  74. /// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
  75. /// <param name="value">The value.</param>
  76. /// <param name="serializer">The calling serializer.</param>
  77. public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  78. {
  79. if (value == null)
  80. {
  81. writer.WriteNull();
  82. return;
  83. }
  84. Enum e = (Enum)value;
  85. if (!EnumUtils.TryToString(e.GetType(), value, CamelCaseText, out string enumName))
  86. {
  87. if (!AllowIntegerValues)
  88. {
  89. throw JsonSerializationException.Create(null, writer.ContainerPath, "Integer value {0} is not allowed.".FormatWith(CultureInfo.InvariantCulture, e.ToString("D")), null);
  90. }
  91. // enum value has no name so write number
  92. writer.WriteValue(value);
  93. }
  94. else
  95. {
  96. writer.WriteValue(enumName);
  97. }
  98. }
  99. /// <summary>
  100. /// Reads the JSON representation of the object.
  101. /// </summary>
  102. /// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
  103. /// <param name="objectType">Type of the object.</param>
  104. /// <param name="existingValue">The existing value of object being read.</param>
  105. /// <param name="serializer">The calling serializer.</param>
  106. /// <returns>The object value.</returns>
  107. public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
  108. {
  109. if (reader.TokenType == JsonToken.Null)
  110. {
  111. if (!ReflectionUtils.IsNullableType(objectType))
  112. {
  113. throw JsonSerializationException.Create(reader, "Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType));
  114. }
  115. return null;
  116. }
  117. bool isNullable = ReflectionUtils.IsNullableType(objectType);
  118. Type t = isNullable ? Nullable.GetUnderlyingType(objectType) : objectType;
  119. try
  120. {
  121. if (reader.TokenType == JsonToken.String)
  122. {
  123. string enumText = reader.Value.ToString();
  124. if (enumText == string.Empty && isNullable)
  125. {
  126. return null;
  127. }
  128. return EnumUtils.ParseEnum(t, enumText, !AllowIntegerValues);
  129. }
  130. if (reader.TokenType == JsonToken.Integer)
  131. {
  132. if (!AllowIntegerValues)
  133. {
  134. throw JsonSerializationException.Create(reader, "Integer value {0} is not allowed.".FormatWith(CultureInfo.InvariantCulture, reader.Value));
  135. }
  136. return ConvertUtils.ConvertOrCast(reader.Value, CultureInfo.InvariantCulture, t);
  137. }
  138. }
  139. catch (Exception ex)
  140. {
  141. throw JsonSerializationException.Create(reader, "Error converting value {0} to type '{1}'.".FormatWith(CultureInfo.InvariantCulture, MiscellaneousUtils.FormatValueForPrint(reader.Value), objectType), ex);
  142. }
  143. // we don't actually expect to get here.
  144. throw JsonSerializationException.Create(reader, "Unexpected token {0} when parsing enum.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
  145. }
  146. /// <summary>
  147. /// Determines whether this instance can convert the specified object type.
  148. /// </summary>
  149. /// <param name="objectType">Type of the object.</param>
  150. /// <returns>
  151. /// <c>true</c> if this instance can convert the specified object type; otherwise, <c>false</c>.
  152. /// </returns>
  153. public override bool CanConvert(Type objectType)
  154. {
  155. Type t = (ReflectionUtils.IsNullableType(objectType))
  156. ? Nullable.GetUnderlyingType(objectType)
  157. : objectType;
  158. return t.IsEnum();
  159. }
  160. }
  161. }