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.

207 lines
7.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 || HAVE_ADO_NET
  26. using System;
  27. using System.Globalization;
  28. using Newtonsoft.Json.Utilities;
  29. using System.Collections.Generic;
  30. #if HAVE_ADO_NET
  31. using System.Data.SqlTypes;
  32. #endif
  33. namespace Newtonsoft.Json.Converters
  34. {
  35. /// <summary>
  36. /// Converts a binary value to and from a base 64 string value.
  37. /// </summary>
  38. internal class BinaryConverter : JsonConverter
  39. {
  40. #if !NET20
  41. private const string BinaryTypeName = "System.Data.Linq.Binary";
  42. private const string BinaryToArrayName = "ToArray";
  43. private static ReflectionObject _reflectionObject;
  44. #endif
  45. /// <summary>
  46. /// Writes the JSON representation of the object.
  47. /// </summary>
  48. /// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
  49. /// <param name="value">The value.</param>
  50. /// <param name="serializer">The calling serializer.</param>
  51. public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  52. {
  53. if (value == null)
  54. {
  55. writer.WriteNull();
  56. return;
  57. }
  58. byte[] data = GetByteArray(value);
  59. writer.WriteValue(data);
  60. }
  61. private byte[] GetByteArray(object value)
  62. {
  63. #if !NET20
  64. if (value.GetType().FullName == BinaryTypeName)
  65. {
  66. EnsureReflectionObject(value.GetType());
  67. return (byte[])_reflectionObject.GetValue(value, BinaryToArrayName);
  68. }
  69. #endif
  70. #if HAVE_ADO_NET
  71. if (value is SqlBinary binary)
  72. {
  73. return binary.Value;
  74. }
  75. #endif
  76. throw new JsonSerializationException("Unexpected value type when writing binary: {0}".FormatWith(CultureInfo.InvariantCulture, value.GetType()));
  77. }
  78. #if !NET20
  79. private static void EnsureReflectionObject(Type t)
  80. {
  81. if (_reflectionObject == null)
  82. {
  83. _reflectionObject = ReflectionObject.Create(t, t.GetConstructor(new[] { typeof(byte[]) }), BinaryToArrayName);
  84. }
  85. }
  86. #endif
  87. /// <summary>
  88. /// Reads the JSON representation of the object.
  89. /// </summary>
  90. /// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
  91. /// <param name="objectType">Type of the object.</param>
  92. /// <param name="existingValue">The existing value of object being read.</param>
  93. /// <param name="serializer">The calling serializer.</param>
  94. /// <returns>The object value.</returns>
  95. public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
  96. {
  97. if (reader.TokenType == JsonToken.Null)
  98. {
  99. if (!ReflectionUtils.IsNullable(objectType))
  100. {
  101. throw JsonSerializationException.Create(reader, "Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType));
  102. }
  103. return null;
  104. }
  105. byte[] data;
  106. if (reader.TokenType == JsonToken.StartArray)
  107. {
  108. data = ReadByteArray(reader);
  109. }
  110. else if (reader.TokenType == JsonToken.String)
  111. {
  112. // current token is already at base64 string
  113. // unable to call ReadAsBytes so do it the old fashion way
  114. string encodedData = reader.Value.ToString();
  115. data = Convert.FromBase64String(encodedData);
  116. }
  117. else
  118. {
  119. throw JsonSerializationException.Create(reader, "Unexpected token parsing binary. Expected String or StartArray, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
  120. }
  121. Type t = (ReflectionUtils.IsNullableType(objectType))
  122. ? Nullable.GetUnderlyingType(objectType)
  123. : objectType;
  124. #if !NET20
  125. if (t.FullName == BinaryTypeName)
  126. {
  127. EnsureReflectionObject(t);
  128. return _reflectionObject.Creator(data);
  129. }
  130. #endif
  131. #if HAVE_ADO_NET
  132. if (t == typeof(SqlBinary))
  133. {
  134. return new SqlBinary(data);
  135. }
  136. #endif
  137. throw JsonSerializationException.Create(reader, "Unexpected object type when writing binary: {0}".FormatWith(CultureInfo.InvariantCulture, objectType));
  138. }
  139. private byte[] ReadByteArray(JsonReader reader)
  140. {
  141. List<byte> byteList = new List<byte>();
  142. while (reader.Read())
  143. {
  144. switch (reader.TokenType)
  145. {
  146. case JsonToken.Integer:
  147. byteList.Add(Convert.ToByte(reader.Value, CultureInfo.InvariantCulture));
  148. break;
  149. case JsonToken.EndArray:
  150. return byteList.ToArray();
  151. case JsonToken.Comment:
  152. // skip
  153. break;
  154. default:
  155. throw JsonSerializationException.Create(reader, "Unexpected token when reading bytes: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
  156. }
  157. }
  158. throw JsonSerializationException.Create(reader, "Unexpected end when reading bytes.");
  159. }
  160. /// <summary>
  161. /// Determines whether this instance can convert the specified object type.
  162. /// </summary>
  163. /// <param name="objectType">Type of the object.</param>
  164. /// <returns>
  165. /// <c>true</c> if this instance can convert the specified object type; otherwise, <c>false</c>.
  166. /// </returns>
  167. public override bool CanConvert(Type objectType)
  168. {
  169. #if !NET20
  170. if (objectType.FullName == BinaryTypeName)
  171. {
  172. return true;
  173. }
  174. #endif
  175. #if HAVE_ADO_NET
  176. if (objectType == typeof(SqlBinary) || objectType == typeof(SqlBinary?))
  177. {
  178. return true;
  179. }
  180. #endif
  181. return false;
  182. }
  183. }
  184. }
  185. #endif