PageRenderTime 50ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/Json45r7/Source/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs

https://bitbucket.org/wantstudios/bitbucketclient
C# | 1460 lines | 1329 code | 92 blank | 39 comment | 210 complexity | 0bf72d8855bea345f796ee8278a14dc6 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  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;
  27. using System.Collections.Generic;
  28. using System.Collections.ObjectModel;
  29. #if !(NET35 || NET20 || WINDOWS_PHONE || PORTABLE)
  30. using System.Dynamic;
  31. #endif
  32. using System.Globalization;
  33. using System.Reflection;
  34. using System.Runtime.Serialization;
  35. using Newtonsoft.Json.Linq;
  36. using Newtonsoft.Json.Utilities;
  37. #if NET20
  38. using Newtonsoft.Json.Utilities.LinqBridge;
  39. #else
  40. using System.Linq;
  41. #endif
  42. namespace Newtonsoft.Json.Serialization
  43. {
  44. internal class JsonSerializerInternalReader : JsonSerializerInternalBase
  45. {
  46. private JsonSerializerProxy _internalSerializer;
  47. #if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
  48. private JsonFormatterConverter _formatterConverter;
  49. #endif
  50. public JsonSerializerInternalReader(JsonSerializer serializer)
  51. : base(serializer)
  52. {
  53. }
  54. public void Populate(JsonReader reader, object target)
  55. {
  56. ValidationUtils.ArgumentNotNull(target, "target");
  57. Type objectType = target.GetType();
  58. JsonContract contract = Serializer.ContractResolver.ResolveContract(objectType);
  59. if (reader.TokenType == JsonToken.None)
  60. reader.Read();
  61. if (reader.TokenType == JsonToken.StartArray)
  62. {
  63. if (contract.ContractType == JsonContractType.Array)
  64. PopulateList(CollectionUtils.CreateCollectionWrapper(target), reader, (JsonArrayContract) contract, null, null);
  65. else
  66. throw JsonSerializationException.Create(reader, "Cannot populate JSON array onto type '{0}'.".FormatWith(CultureInfo.InvariantCulture, objectType));
  67. }
  68. else if (reader.TokenType == JsonToken.StartObject)
  69. {
  70. CheckedRead(reader);
  71. string id = null;
  72. if (reader.TokenType == JsonToken.PropertyName && string.Equals(reader.Value.ToString(), JsonTypeReflector.IdPropertyName, StringComparison.Ordinal))
  73. {
  74. CheckedRead(reader);
  75. id = (reader.Value != null) ? reader.Value.ToString() : null;
  76. CheckedRead(reader);
  77. }
  78. if (contract.ContractType == JsonContractType.Dictionary)
  79. PopulateDictionary(CollectionUtils.CreateDictionaryWrapper(target), reader, (JsonDictionaryContract) contract, null, id);
  80. else if (contract.ContractType == JsonContractType.Object)
  81. PopulateObject(target, reader, (JsonObjectContract) contract, null, id);
  82. else
  83. throw JsonSerializationException.Create(reader, "Cannot populate JSON object onto type '{0}'.".FormatWith(CultureInfo.InvariantCulture, objectType));
  84. }
  85. else
  86. {
  87. throw JsonSerializationException.Create(reader, "Unexpected initial token '{0}' when populating object. Expected JSON object or array.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
  88. }
  89. }
  90. private JsonContract GetContractSafe(Type type)
  91. {
  92. if (type == null)
  93. return null;
  94. return Serializer.ContractResolver.ResolveContract(type);
  95. }
  96. public object Deserialize(JsonReader reader, Type objectType, bool checkAdditionalContent)
  97. {
  98. if (reader == null)
  99. throw new ArgumentNullException("reader");
  100. JsonContract contract = GetContractSafe(objectType);
  101. try
  102. {
  103. JsonConverter converter = GetConverter(contract, null, null, null);
  104. if (reader.TokenType == JsonToken.None && !ReadForType(reader, contract, converter != null))
  105. {
  106. if (contract != null && !contract.IsNullable)
  107. throw JsonSerializationException.Create(reader, "No JSON content found and type '{0}' is not nullable.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType));
  108. return null;
  109. }
  110. object deserializedValue;
  111. if (converter != null && converter.CanRead)
  112. deserializedValue = converter.ReadJson(reader, objectType, null, GetInternalSerializer());
  113. else
  114. deserializedValue = CreateValueInternal(reader, objectType, contract, null, null, null, null);
  115. if (checkAdditionalContent)
  116. {
  117. if (reader.Read() && reader.TokenType != JsonToken.Comment)
  118. throw new JsonSerializationException("Additional text found in JSON string after finishing deserializing object.");
  119. }
  120. return deserializedValue;
  121. }
  122. catch (Exception ex)
  123. {
  124. if (IsErrorHandled(null, contract, null, reader.Path, ex))
  125. {
  126. HandleError(reader, false, 0);
  127. return null;
  128. }
  129. else
  130. {
  131. throw;
  132. }
  133. }
  134. }
  135. private JsonSerializerProxy GetInternalSerializer()
  136. {
  137. if (_internalSerializer == null)
  138. _internalSerializer = new JsonSerializerProxy(this);
  139. return _internalSerializer;
  140. }
  141. #if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
  142. private JsonFormatterConverter GetFormatterConverter()
  143. {
  144. if (_formatterConverter == null)
  145. _formatterConverter = new JsonFormatterConverter(GetInternalSerializer());
  146. return _formatterConverter;
  147. }
  148. #endif
  149. private JToken CreateJToken(JsonReader reader, JsonContract contract)
  150. {
  151. ValidationUtils.ArgumentNotNull(reader, "reader");
  152. if (contract != null && contract.UnderlyingType == typeof (JRaw))
  153. {
  154. return JRaw.Create(reader);
  155. }
  156. else
  157. {
  158. JToken token;
  159. using (JTokenWriter writer = new JTokenWriter())
  160. {
  161. writer.WriteToken(reader);
  162. token = writer.Token;
  163. }
  164. return token;
  165. }
  166. }
  167. private JToken CreateJObject(JsonReader reader)
  168. {
  169. ValidationUtils.ArgumentNotNull(reader, "reader");
  170. // this is needed because we've already read inside the object, looking for special properties
  171. JToken token;
  172. using (JTokenWriter writer = new JTokenWriter())
  173. {
  174. writer.WriteStartObject();
  175. if (reader.TokenType == JsonToken.PropertyName)
  176. writer.WriteToken(reader, reader.Depth - 1);
  177. else
  178. writer.WriteEndObject();
  179. token = writer.Token;
  180. }
  181. return token;
  182. }
  183. private object CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, object existingValue)
  184. {
  185. if (contract != null && contract.ContractType == JsonContractType.Linq)
  186. return CreateJToken(reader, contract);
  187. do
  188. {
  189. switch (reader.TokenType)
  190. {
  191. // populate a typed object or generic dictionary/array
  192. // depending upon whether an objectType was supplied
  193. case JsonToken.StartObject:
  194. return CreateObject(reader, objectType, contract, member, containerContract, containerMember, existingValue);
  195. case JsonToken.StartArray:
  196. return CreateList(reader, objectType, contract, member, existingValue, null);
  197. case JsonToken.Integer:
  198. case JsonToken.Float:
  199. case JsonToken.Boolean:
  200. case JsonToken.Date:
  201. case JsonToken.Bytes:
  202. return EnsureType(reader, reader.Value, CultureInfo.InvariantCulture, contract, objectType);
  203. case JsonToken.String:
  204. // convert empty string to null automatically for nullable types
  205. if (string.IsNullOrEmpty((string)reader.Value) && objectType != typeof(string) && objectType != typeof(object) && contract != null && contract.IsNullable)
  206. return null;
  207. // string that needs to be returned as a byte array should be base 64 decoded
  208. if (objectType == typeof (byte[]))
  209. return Convert.FromBase64String((string) reader.Value);
  210. return EnsureType(reader, reader.Value, CultureInfo.InvariantCulture, contract, objectType);
  211. case JsonToken.StartConstructor:
  212. string constructorName = reader.Value.ToString();
  213. return EnsureType(reader, constructorName, CultureInfo.InvariantCulture, contract, objectType);
  214. case JsonToken.Null:
  215. case JsonToken.Undefined:
  216. #if !(NETFX_CORE || PORTABLE)
  217. if (objectType == typeof (DBNull))
  218. return DBNull.Value;
  219. #endif
  220. return EnsureType(reader, reader.Value, CultureInfo.InvariantCulture, contract, objectType);
  221. case JsonToken.Raw:
  222. return new JRaw((string) reader.Value);
  223. case JsonToken.Comment:
  224. // ignore
  225. break;
  226. default:
  227. throw JsonSerializationException.Create(reader, "Unexpected token while deserializing object: " + reader.TokenType);
  228. }
  229. } while (reader.Read());
  230. throw JsonSerializationException.Create(reader, "Unexpected end when deserializing object.");
  231. }
  232. internal string GetExpectedDescription(JsonContract contract)
  233. {
  234. switch (contract.ContractType)
  235. {
  236. case JsonContractType.Object:
  237. case JsonContractType.Dictionary:
  238. #if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
  239. case JsonContractType.Serializable:
  240. #endif
  241. #if !(NET35 || NET20 || WINDOWS_PHONE || PORTABLE)
  242. case JsonContractType.Dynamic:
  243. #endif
  244. return @"JSON object (e.g. {""name"":""value""})";
  245. case JsonContractType.Array:
  246. return @"JSON array (e.g. [1,2,3])";
  247. case JsonContractType.Primitive:
  248. return @"JSON primitive value (e.g. string, number, boolean, null)";
  249. case JsonContractType.String:
  250. return @"JSON string value";
  251. default:
  252. throw new ArgumentOutOfRangeException();
  253. }
  254. }
  255. private JsonConverter GetConverter(JsonContract contract, JsonConverter memberConverter, JsonContainerContract containerContract, JsonProperty containerProperty)
  256. {
  257. JsonConverter converter = null;
  258. if (memberConverter != null)
  259. {
  260. // member attribute converter
  261. converter = memberConverter;
  262. }
  263. else if (containerProperty != null && containerProperty.ItemConverter != null)
  264. {
  265. converter = containerProperty.ItemConverter;
  266. }
  267. else if (containerContract != null && containerContract.ItemConverter != null)
  268. {
  269. converter = containerContract.ItemConverter;
  270. }
  271. else if (contract != null)
  272. {
  273. JsonConverter matchingConverter;
  274. if (contract.Converter != null)
  275. // class attribute converter
  276. converter = contract.Converter;
  277. else if ((matchingConverter = Serializer.GetMatchingConverter(contract.UnderlyingType)) != null)
  278. // passed in converters
  279. converter = matchingConverter;
  280. else if (contract.InternalConverter != null)
  281. // internally specified converter
  282. converter = contract.InternalConverter;
  283. }
  284. return converter;
  285. }
  286. private object CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, object existingValue)
  287. {
  288. CheckedRead(reader);
  289. string id;
  290. object newValue;
  291. if (ReadSpecialProperties(reader, ref objectType, ref contract, member, containerContract, containerMember, existingValue, out newValue, out id))
  292. return newValue;
  293. if (!HasDefinedType(objectType))
  294. return CreateJObject(reader);
  295. if (contract == null)
  296. throw JsonSerializationException.Create(reader, "Could not resolve type '{0}' to a JsonContract.".FormatWith(CultureInfo.InvariantCulture, objectType));
  297. switch (contract.ContractType)
  298. {
  299. case JsonContractType.Object:
  300. bool createdFromNonDefaultConstructor = false;
  301. JsonObjectContract objectContract = (JsonObjectContract) contract;
  302. object targetObject;
  303. if (existingValue != null)
  304. targetObject = existingValue;
  305. else
  306. targetObject = CreateNewObject(reader, objectContract, member, containerMember, id, out createdFromNonDefaultConstructor);
  307. // don't populate if read from non-default constructor because the object has already been read
  308. if (createdFromNonDefaultConstructor)
  309. return targetObject;
  310. return PopulateObject(targetObject, reader, objectContract, member, id);
  311. case JsonContractType.Primitive:
  312. JsonPrimitiveContract primitiveContract = (JsonPrimitiveContract) contract;
  313. // if the content is inside $value then read past it
  314. if (reader.TokenType == JsonToken.PropertyName && string.Equals(reader.Value.ToString(), JsonTypeReflector.ValuePropertyName, StringComparison.Ordinal))
  315. {
  316. CheckedRead(reader);
  317. object value = CreateValueInternal(reader, objectType, primitiveContract, member, null, null, existingValue);
  318. CheckedRead(reader);
  319. return value;
  320. }
  321. break;
  322. case JsonContractType.Dictionary:
  323. JsonDictionaryContract dictionaryContract = (JsonDictionaryContract) contract;
  324. object targetDictionary;
  325. if (existingValue != null)
  326. targetDictionary = existingValue;
  327. else
  328. targetDictionary = CreateNewDictionary(reader, dictionaryContract);
  329. return PopulateDictionary(dictionaryContract.CreateWrapper(targetDictionary), reader, dictionaryContract, member, id);
  330. #if !(NET35 || NET20 || WINDOWS_PHONE || PORTABLE)
  331. case JsonContractType.Dynamic:
  332. JsonDynamicContract dynamicContract = (JsonDynamicContract) contract;
  333. return CreateDynamic(reader, dynamicContract, member, id);
  334. #endif
  335. #if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
  336. case JsonContractType.Serializable:
  337. JsonISerializableContract serializableContract = (JsonISerializableContract) contract;
  338. return CreateISerializable(reader, serializableContract, id);
  339. #endif
  340. }
  341. throw JsonSerializationException.Create(reader, @"Cannot deserialize the current JSON object (e.g. {{""name"":""value""}}) into type '{0}' because the type requires a {1} to deserialize correctly.
  342. To fix this error either change the JSON to a {1} or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
  343. ".FormatWith(CultureInfo.InvariantCulture, objectType, GetExpectedDescription(contract)));
  344. }
  345. private bool ReadSpecialProperties(JsonReader reader, ref Type objectType, ref JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, object existingValue, out object newValue, out string id)
  346. {
  347. id = null;
  348. newValue = null;
  349. if (reader.TokenType == JsonToken.PropertyName)
  350. {
  351. string propertyName = reader.Value.ToString();
  352. if (propertyName.Length > 0 && propertyName[0] == '$')
  353. {
  354. // read 'special' properties
  355. // $type, $id, $ref, etc
  356. bool specialProperty;
  357. do
  358. {
  359. propertyName = reader.Value.ToString();
  360. if (string.Equals(propertyName, JsonTypeReflector.RefPropertyName, StringComparison.Ordinal))
  361. {
  362. CheckedRead(reader);
  363. if (reader.TokenType != JsonToken.String && reader.TokenType != JsonToken.Null)
  364. throw JsonSerializationException.Create(reader, "JSON reference {0} property must have a string or null value.".FormatWith(CultureInfo.InvariantCulture, JsonTypeReflector.RefPropertyName));
  365. string reference = (reader.Value != null) ? reader.Value.ToString() : null;
  366. CheckedRead(reader);
  367. if (reference != null)
  368. {
  369. if (reader.TokenType == JsonToken.PropertyName)
  370. throw JsonSerializationException.Create(reader, "Additional content found in JSON reference object. A JSON reference object should only have a {0} property.".FormatWith(CultureInfo.InvariantCulture, JsonTypeReflector.RefPropertyName));
  371. {
  372. newValue = Serializer.ReferenceResolver.ResolveReference(this, reference);
  373. return true;
  374. }
  375. }
  376. else
  377. {
  378. specialProperty = true;
  379. }
  380. }
  381. else if (string.Equals(propertyName, JsonTypeReflector.TypePropertyName, StringComparison.Ordinal))
  382. {
  383. CheckedRead(reader);
  384. string qualifiedTypeName = reader.Value.ToString();
  385. TypeNameHandling resolvedTypeNameHandling =
  386. ((member != null) ? member.TypeNameHandling : null)
  387. ?? ((containerContract != null) ? containerContract.ItemTypeNameHandling : null)
  388. ?? ((containerMember != null) ? containerMember.ItemTypeNameHandling : null)
  389. ?? Serializer.TypeNameHandling;
  390. if (resolvedTypeNameHandling != TypeNameHandling.None)
  391. {
  392. string typeName;
  393. string assemblyName;
  394. ReflectionUtils.SplitFullyQualifiedTypeName(qualifiedTypeName, out typeName, out assemblyName);
  395. Type specifiedType;
  396. try
  397. {
  398. specifiedType = Serializer.Binder.BindToType(assemblyName, typeName);
  399. }
  400. catch (Exception ex)
  401. {
  402. throw JsonSerializationException.Create(reader, "Error resolving type specified in JSON '{0}'.".FormatWith(CultureInfo.InvariantCulture, qualifiedTypeName), ex);
  403. }
  404. if (specifiedType == null)
  405. throw JsonSerializationException.Create(reader, "Type specified in JSON '{0}' was not resolved.".FormatWith(CultureInfo.InvariantCulture, qualifiedTypeName));
  406. if (objectType != null
  407. #if !(NET35 || NET20 || WINDOWS_PHONE || PORTABLE)
  408. && objectType != typeof (IDynamicMetaObjectProvider)
  409. #endif
  410. && !objectType.IsAssignableFrom(specifiedType))
  411. throw JsonSerializationException.Create(reader, "Type specified in JSON '{0}' is not compatible with '{1}'.".FormatWith(CultureInfo.InvariantCulture, specifiedType.AssemblyQualifiedName, objectType.AssemblyQualifiedName));
  412. objectType = specifiedType;
  413. contract = GetContractSafe(specifiedType);
  414. }
  415. CheckedRead(reader);
  416. specialProperty = true;
  417. }
  418. else if (string.Equals(propertyName, JsonTypeReflector.IdPropertyName, StringComparison.Ordinal))
  419. {
  420. CheckedRead(reader);
  421. id = (reader.Value != null) ? reader.Value.ToString() : null;
  422. CheckedRead(reader);
  423. specialProperty = true;
  424. }
  425. else if (string.Equals(propertyName, JsonTypeReflector.ArrayValuesPropertyName, StringComparison.Ordinal))
  426. {
  427. CheckedRead(reader);
  428. object list = CreateList(reader, objectType, contract, member, existingValue, id);
  429. CheckedRead(reader);
  430. newValue = list;
  431. return true;
  432. }
  433. else
  434. {
  435. specialProperty = false;
  436. }
  437. } while (specialProperty
  438. && reader.TokenType == JsonToken.PropertyName);
  439. }
  440. }
  441. return false;
  442. }
  443. private JsonArrayContract EnsureArrayContract(JsonReader reader, Type objectType, JsonContract contract)
  444. {
  445. if (contract == null)
  446. throw JsonSerializationException.Create(reader, "Could not resolve type '{0}' to a JsonContract.".FormatWith(CultureInfo.InvariantCulture, objectType));
  447. JsonArrayContract arrayContract = contract as JsonArrayContract;
  448. if (arrayContract == null)
  449. throw JsonSerializationException.Create(reader, @"Cannot deserialize the current JSON array (e.g. [1,2,3]) into type '{0}' because the type requires a {1} to deserialize correctly.
  450. To fix this error either change the JSON to a {1} or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
  451. ".FormatWith(CultureInfo.InvariantCulture, objectType, GetExpectedDescription(contract)));
  452. return arrayContract;
  453. }
  454. private void CheckedRead(JsonReader reader)
  455. {
  456. if (!reader.Read())
  457. throw JsonSerializationException.Create(reader, "Unexpected end when deserializing object.");
  458. }
  459. private object CreateList(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, object existingValue, string id)
  460. {
  461. object value;
  462. if (HasDefinedType(objectType))
  463. {
  464. JsonArrayContract arrayContract = EnsureArrayContract(reader, objectType, contract);
  465. if (existingValue == null)
  466. {
  467. bool isTemporaryListReference;
  468. IList list = CollectionUtils.CreateList(contract.CreatedType, out isTemporaryListReference);
  469. if (id != null && isTemporaryListReference)
  470. throw JsonSerializationException.Create(reader, "Cannot preserve reference to array or readonly list: {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType));
  471. #if !PocketPC
  472. if (contract.OnSerializing != null && isTemporaryListReference)
  473. throw JsonSerializationException.Create(reader, "Cannot call OnSerializing on an array or readonly list: {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType));
  474. #endif
  475. if (contract.OnError != null && isTemporaryListReference)
  476. throw JsonSerializationException.Create(reader, "Cannot call OnError on an array or readonly list: {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType));
  477. PopulateList(arrayContract.CreateWrapper(list), reader, arrayContract, member, id);
  478. // create readonly and fixed sized collections using the temporary list
  479. if (isTemporaryListReference)
  480. {
  481. if (contract.CreatedType.IsArray)
  482. list = CollectionUtils.ToArray(((List<object>)list).ToArray(), ReflectionUtils.GetCollectionItemType(contract.CreatedType));
  483. else if (ReflectionUtils.InheritsGenericDefinition(contract.CreatedType, typeof(ReadOnlyCollection<>)))
  484. list = (IList)ReflectionUtils.CreateInstance(contract.CreatedType, list);
  485. }
  486. else if (list is IWrappedCollection)
  487. {
  488. return ((IWrappedCollection)list).UnderlyingCollection;
  489. }
  490. value = list;
  491. }
  492. else
  493. {
  494. value = PopulateList(arrayContract.CreateWrapper(existingValue), reader, arrayContract, member, id);
  495. }
  496. }
  497. else
  498. {
  499. value = CreateJToken(reader, contract);
  500. }
  501. return value;
  502. }
  503. private bool HasDefinedType(Type type)
  504. {
  505. return (type != null && type != typeof (object) && !typeof (JToken).IsSubclassOf(type)
  506. #if !(NET35 || NET20 || WINDOWS_PHONE || PORTABLE)
  507. && type != typeof (IDynamicMetaObjectProvider)
  508. #endif
  509. );
  510. }
  511. private object EnsureType(JsonReader reader, object value, CultureInfo culture, JsonContract contract, Type targetType)
  512. {
  513. if (targetType == null)
  514. return value;
  515. Type valueType = ReflectionUtils.GetObjectType(value);
  516. // type of value and type of target don't match
  517. // attempt to convert value's type to target's type
  518. if (valueType != targetType)
  519. {
  520. try
  521. {
  522. if (value == null && contract.IsNullable)
  523. return null;
  524. if (contract.IsConvertable)
  525. {
  526. if (contract.NonNullableUnderlyingType.IsEnum())
  527. {
  528. if (value is string)
  529. return Enum.Parse(contract.NonNullableUnderlyingType, value.ToString(), true);
  530. else if (ConvertUtils.IsInteger(value))
  531. return Enum.ToObject(contract.NonNullableUnderlyingType, value);
  532. }
  533. return Convert.ChangeType(value, contract.NonNullableUnderlyingType, culture);
  534. }
  535. return ConvertUtils.ConvertOrCast(value, culture, contract.NonNullableUnderlyingType);
  536. }
  537. catch (Exception ex)
  538. {
  539. throw JsonSerializationException.Create(reader, "Error converting value {0} to type '{1}'.".FormatWith(CultureInfo.InvariantCulture, FormatValueForPrint(value), targetType), ex);
  540. }
  541. }
  542. return value;
  543. }
  544. private string FormatValueForPrint(object value)
  545. {
  546. if (value == null)
  547. return "{null}";
  548. if (value is string)
  549. return @"""" + value + @"""";
  550. return value.ToString();
  551. }
  552. private void SetPropertyValue(JsonProperty property, JsonConverter propertyConverter, JsonContainerContract containerContract, JsonProperty containerProperty, JsonReader reader, object target)
  553. {
  554. object currentValue;
  555. bool useExistingValue;
  556. JsonContract propertyContract;
  557. bool gottenCurrentValue;
  558. if (CalculatePropertyDetails(property, ref propertyConverter, containerContract, containerProperty, reader, target, out useExistingValue, out currentValue, out propertyContract, out gottenCurrentValue))
  559. return;
  560. object value;
  561. if (propertyConverter != null && propertyConverter.CanRead)
  562. {
  563. if (!gottenCurrentValue && target != null && property.Readable)
  564. currentValue = property.ValueProvider.GetValue(target);
  565. value = propertyConverter.ReadJson(reader, property.PropertyType, currentValue, GetInternalSerializer());
  566. }
  567. else
  568. {
  569. value = CreateValueInternal(reader, property.PropertyType, propertyContract, property, containerContract, containerProperty, (useExistingValue) ? currentValue : null);
  570. }
  571. // always set the value if useExistingValue is false,
  572. // otherwise also set it if CreateValue returns a new value compared to the currentValue
  573. // this could happen because of a JsonConverter against the type
  574. if ((!useExistingValue || value != currentValue)
  575. && ShouldSetPropertyValue(property, value))
  576. {
  577. property.ValueProvider.SetValue(target, value);
  578. if (property.SetIsSpecified != null)
  579. property.SetIsSpecified(target, true);
  580. }
  581. }
  582. private bool CalculatePropertyDetails(JsonProperty property, ref JsonConverter propertyConverter, JsonContainerContract containerContract, JsonProperty containerProperty, JsonReader reader, object target, out bool useExistingValue, out object currentValue, out JsonContract propertyContract, out bool gottenCurrentValue)
  583. {
  584. currentValue = null;
  585. useExistingValue = false;
  586. propertyContract = null;
  587. gottenCurrentValue = false;
  588. if (property.Ignored)
  589. {
  590. reader.Skip();
  591. return true;
  592. }
  593. ObjectCreationHandling objectCreationHandling =
  594. property.ObjectCreationHandling.GetValueOrDefault(Serializer.ObjectCreationHandling);
  595. if ((objectCreationHandling == ObjectCreationHandling.Auto || objectCreationHandling == ObjectCreationHandling.Reuse)
  596. && (reader.TokenType == JsonToken.StartArray || reader.TokenType == JsonToken.StartObject)
  597. && property.Readable)
  598. {
  599. currentValue = property.ValueProvider.GetValue(target);
  600. gottenCurrentValue = true;
  601. useExistingValue = (currentValue != null
  602. && !property.PropertyType.IsArray
  603. && !ReflectionUtils.InheritsGenericDefinition(property.PropertyType, typeof (ReadOnlyCollection<>))
  604. && !property.PropertyType.IsValueType());
  605. }
  606. if (!property.Writable && !useExistingValue)
  607. {
  608. reader.Skip();
  609. return true;
  610. }
  611. // test tokentype here because null might not be convertable to some types, e.g. ignoring null when applied to DateTime
  612. if (property.NullValueHandling.GetValueOrDefault(Serializer.NullValueHandling) == NullValueHandling.Ignore && reader.TokenType == JsonToken.Null)
  613. {
  614. reader.Skip();
  615. return true;
  616. }
  617. // test tokentype here because default value might not be convertable to actual type, e.g. default of "" for DateTime
  618. if (HasFlag(property.DefaultValueHandling.GetValueOrDefault(Serializer.DefaultValueHandling), DefaultValueHandling.Ignore)
  619. && JsonReader.IsPrimitiveToken(reader.TokenType)
  620. && MiscellaneousUtils.ValueEquals(reader.Value, property.DefaultValue))
  621. {
  622. reader.Skip();
  623. return true;
  624. }
  625. if (property.PropertyContract == null)
  626. property.PropertyContract = GetContractSafe(property.PropertyType);
  627. if (currentValue == null)
  628. {
  629. propertyContract = property.PropertyContract;
  630. }
  631. else
  632. {
  633. propertyContract = GetContractSafe(currentValue.GetType());
  634. if (propertyContract != property.PropertyContract)
  635. propertyConverter = GetConverter(propertyContract, property.MemberConverter, containerContract, containerProperty);
  636. }
  637. return false;
  638. }
  639. private bool HasFlag(DefaultValueHandling value, DefaultValueHandling flag)
  640. {
  641. return ((value & flag) == flag);
  642. }
  643. private bool ShouldSetPropertyValue(JsonProperty property, object value)
  644. {
  645. if (property.NullValueHandling.GetValueOrDefault(Serializer.NullValueHandling) == NullValueHandling.Ignore && value == null)
  646. return false;
  647. if (HasFlag(property.DefaultValueHandling.GetValueOrDefault(Serializer.DefaultValueHandling), DefaultValueHandling.Ignore)
  648. && MiscellaneousUtils.ValueEquals(value, property.DefaultValue))
  649. return false;
  650. if (!property.Writable)
  651. return false;
  652. return true;
  653. }
  654. public object CreateNewDictionary(JsonReader reader, JsonDictionaryContract contract)
  655. {
  656. object dictionary;
  657. if (contract.DefaultCreator != null &&
  658. (!contract.DefaultCreatorNonPublic || Serializer.ConstructorHandling == ConstructorHandling.AllowNonPublicDefaultConstructor))
  659. dictionary = contract.DefaultCreator();
  660. else
  661. throw JsonSerializationException.Create(reader, "Unable to find a default constructor to use for type {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType));
  662. return dictionary;
  663. }
  664. private object PopulateDictionary(IWrappedDictionary wrappedDictionary, JsonReader reader, JsonDictionaryContract contract, JsonProperty containerProperty, string id)
  665. {
  666. object dictionary = wrappedDictionary.UnderlyingDictionary;
  667. if (id != null)
  668. Serializer.ReferenceResolver.AddReference(this, id, dictionary);
  669. contract.InvokeOnDeserializing(dictionary, Serializer.Context);
  670. int initialDepth = reader.Depth;
  671. if (contract.KeyContract == null)
  672. contract.KeyContract = GetContractSafe(contract.DictionaryKeyType);
  673. if (contract.ItemContract == null)
  674. contract.ItemContract = GetContractSafe(contract.DictionaryValueType);
  675. JsonConverter dictionaryValueConverter = contract.ItemConverter ?? GetConverter(contract.ItemContract, null, contract, containerProperty);
  676. do
  677. {
  678. switch (reader.TokenType)
  679. {
  680. case JsonToken.PropertyName:
  681. object keyValue = reader.Value;
  682. try
  683. {
  684. try
  685. {
  686. keyValue = EnsureType(reader, keyValue, CultureInfo.InvariantCulture, contract.KeyContract, contract.DictionaryKeyType);
  687. }
  688. catch (Exception ex)
  689. {
  690. throw JsonSerializationException.Create(reader, "Could not convert string '{0}' to dictionary key type '{1}'. Create a TypeConverter to convert from the string to the key type object.".FormatWith(CultureInfo.InvariantCulture, reader.Value, contract.DictionaryKeyType), ex);
  691. }
  692. if (!ReadForType(reader, contract.ItemContract, dictionaryValueConverter != null))
  693. throw JsonSerializationException.Create(reader, "Unexpected end when deserializing object.");
  694. object itemValue;
  695. if (dictionaryValueConverter != null && dictionaryValueConverter.CanRead)
  696. itemValue = dictionaryValueConverter.ReadJson(reader, contract.DictionaryValueType, null, GetInternalSerializer());
  697. else
  698. itemValue = CreateValueInternal(reader, contract.DictionaryValueType, contract.ItemContract, null, contract, containerProperty, null);
  699. wrappedDictionary[keyValue] = itemValue;
  700. }
  701. catch (Exception ex)
  702. {
  703. if (IsErrorHandled(dictionary, contract, keyValue, reader.Path, ex))
  704. HandleError(reader, true, initialDepth);
  705. else
  706. throw;
  707. }
  708. break;
  709. case JsonToken.Comment:
  710. break;
  711. case JsonToken.EndObject:
  712. contract.InvokeOnDeserialized(dictionary, Serializer.Context);
  713. return dictionary;
  714. default:
  715. throw JsonSerializationException.Create(reader, "Unexpected token when deserializing object: " + reader.TokenType);
  716. }
  717. } while (reader.Read());
  718. throw JsonSerializationException.Create(reader, "Unexpected end when deserializing object.");
  719. }
  720. private object PopulateList(IWrappedCollection wrappedList, JsonReader reader, JsonArrayContract contract, JsonProperty containerProperty, string id)
  721. {
  722. object list = wrappedList.UnderlyingCollection;
  723. if (id != null)
  724. Serializer.ReferenceResolver.AddReference(this, id, list);
  725. // can't populate an existing array
  726. if (wrappedList.IsFixedSize)
  727. {
  728. reader.Skip();
  729. return list;
  730. }
  731. contract.InvokeOnDeserializing(list, Serializer.Context);
  732. int initialDepth = reader.Depth;
  733. JsonContract collectionItemContract = GetContractSafe(contract.CollectionItemType);
  734. JsonConverter collectionItemConverter = GetConverter(collectionItemContract, null, contract, containerProperty);
  735. int? previousErrorIndex = null;
  736. while (true)
  737. {
  738. try
  739. {
  740. if (ReadForType(reader, collectionItemContract, collectionItemConverter != null))
  741. {
  742. switch (reader.TokenType)
  743. {
  744. case JsonToken.EndArray:
  745. contract.InvokeOnDeserialized(list, Serializer.Context);
  746. return list;
  747. case JsonToken.Comment:
  748. break;
  749. default:
  750. object value;
  751. if (collectionItemConverter != null && collectionItemConverter.CanRead)
  752. value = collectionItemConverter.ReadJson(reader, contract.CollectionItemType, null, GetInternalSerializer());
  753. else
  754. value = CreateValueInternal(reader, contract.CollectionItemType, collectionItemContract, null, contract, containerProperty, null);
  755. wrappedList.Add(value);
  756. break;
  757. }
  758. }
  759. else
  760. {
  761. break;
  762. }
  763. }
  764. catch (Exception ex)
  765. {
  766. JsonPosition errorPosition = reader.GetPosition(initialDepth);
  767. if (IsErrorHandled(list, contract, errorPosition.Position, reader.Path, ex))
  768. {
  769. HandleError(reader, true, initialDepth);
  770. if (previousErrorIndex != null && previousErrorIndex == errorPosition.Position)
  771. {
  772. // reader index has not moved since previous error handling
  773. // break out of reading array to prevent infinite loop
  774. throw JsonSerializationException.Create(reader, "Infinite loop detected from error handling.", ex);
  775. }
  776. else
  777. {
  778. previousErrorIndex = errorPosition.Position;
  779. }
  780. }
  781. else
  782. {
  783. throw;
  784. }
  785. }
  786. }
  787. throw JsonSerializationException.Create(reader, "Unexpected end when deserializing array.");
  788. }
  789. #if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
  790. private object CreateISerializable(JsonReader reader, JsonISerializableContract contract, string id)
  791. {
  792. Type objectType = contract.UnderlyingType;
  793. if (!JsonTypeReflector.FullyTrusted)
  794. {
  795. throw JsonSerializationException.Create(reader, @"Type '{0}' implements ISerializable but cannot be deserialized using the ISerializable interface because the current application is not fully trusted and ISerializable can expose secure data.
  796. To fix this error either change the environment to be fully trusted, change the application to not deserialize the type, add JsonObjectAttribute to the type or change the JsonSerializer setting ContractResolver to use a new DefaultContractResolver with IgnoreSerializableInterface set to true.
  797. ".FormatWith(CultureInfo.InvariantCulture, objectType));
  798. }
  799. SerializationInfo serializationInfo = new SerializationInfo(contract.UnderlyingType, GetFormatterConverter());
  800. bool exit = false;
  801. do
  802. {
  803. switch (reader.TokenType)
  804. {
  805. case JsonToken.PropertyName:
  806. string memberName = reader.Value.ToString();
  807. if (!reader.Read())
  808. throw JsonSerializationException.Create(reader, "Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName));
  809. serializationInfo.AddValue(memberName, JToken.ReadFrom(reader));
  810. break;
  811. case JsonToken.Comment:
  812. break;
  813. case JsonToken.EndObject:
  814. exit = true;
  815. break;
  816. default:
  817. throw JsonSerializationException.Create(reader, "Unexpected token when deserializing object: " + reader.TokenType);
  818. }
  819. } while (!exit && reader.Read());
  820. if (contract.ISerializableCreator == null)
  821. throw JsonSerializationException.Create(reader, "ISerializable type '{0}' does not have a valid constructor. To correctly implement ISerializable a constructor that takes SerializationInfo and StreamingContext parameters should be present.".FormatWith(CultureInfo.InvariantCulture, objectType));
  822. object createdObject = contract.ISerializableCreator(serializationInfo, Serializer.Context);
  823. if (id != null)
  824. Serializer.ReferenceResolver.AddReference(this, id, createdObject);
  825. // these are together because OnDeserializing takes an object but for an ISerializable the object is fully created in the constructor
  826. contract.InvokeOnDeserializing(createdObject, Serializer.Context);
  827. contract.InvokeOnDeserialized(createdObject, Serializer.Context);
  828. return createdObject;
  829. }
  830. #endif
  831. #if !(NET35 || NET20 || WINDOWS_PHONE || PORTABLE)
  832. private object CreateDynamic(JsonReader reader, JsonDynamicContract contract, JsonProperty member, string id)
  833. {
  834. IDynamicMetaObjectProvider newObject;
  835. if (contract.UnderlyingType.IsInterface() || contract.UnderlyingType.IsAbstract())
  836. throw JsonSerializationException.Create(reader, "Could not create an instance of type {0}. Type is an interface or abstract class and cannot be instantated.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType));
  837. if (contract.DefaultCreator != null &&
  838. (!contract.DefaultCreatorNonPublic || Serializer.ConstructorHandling == ConstructorHandling.AllowNonPublicDefaultConstructor))
  839. newObject = (IDynamicMetaObjectProvider) contract.DefaultCreator();
  840. else
  841. throw JsonSerializationException.Create(reader, "Unable to find a default constructor to use for type {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType));
  842. if (id != null)
  843. Serializer.ReferenceResolver.AddReference(this, id, newObject);
  844. contract.InvokeOnDeserializing(newObject, Serializer.Context);
  845. int initialDepth = reader.Depth;
  846. bool exit = false;
  847. do
  848. {
  849. switch (reader.TokenType)
  850. {
  851. case JsonToken.PropertyName:
  852. string memberName = reader.Value.ToString();
  853. try
  854. {
  855. if (!reader.Read())
  856. throw JsonSerializationException.Create(reader, "Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName));
  857. // first attempt to find a settable property, otherwise fall back to a dynamic set without type
  858. JsonProperty property = contract.Properties.GetClosestMatchProperty(memberName);
  859. if (property != null && property.Writable && !property.Ignored)
  860. {
  861. if (property.PropertyContract == null)
  862. property.PropertyContract = GetContractSafe(property.PropertyType);
  863. JsonConverter propertyConverter = GetConverter(property.PropertyContract, property.MemberConverter, null, null);
  864. SetPropertyValue(property, propertyConverter, null, member, reader, newObject);
  865. }
  866. else
  867. {
  868. Type t = (JsonReader.IsPrimitiveToken(reader.TokenType)) ? reader.ValueType : typeof (IDynamicMetaObjectProvider);
  869. JsonContract dynamicMemberContract = GetContractSafe(t);
  870. JsonConverter dynamicMemberConverter = GetConverter(dynamicMemberContract, null, null, member);
  871. object value;
  872. if (dynamicMemberConverter != null && dynamicMemberConverter.CanRead)
  873. value = dynamicMemberConverter.ReadJson(reader, t, null, GetInternalSerializer());
  874. else
  875. value = CreateValueInternal(reader, t, dynamicMemberContract, null, null, member, null);
  876. newObject.TrySetMember(memberName, value);
  877. }
  878. }
  879. catch (Exception ex)
  880. {
  881. if (IsErrorHandled(newObject, contract, memberName, reader.Path, ex))
  882. HandleError(reader, true, initialDepth);
  883. else
  884. throw;
  885. }
  886. break;
  887. case JsonToken.EndObject:
  888. exit = true;
  889. break;
  890. default:
  891. throw JsonSerializationException.Create(reader, "Unexpected token when deserializing object: " + reader.TokenType);
  892. }
  893. } while (!exit && reader.Read());
  894. contract.InvokeOnDeserialized(newObject, Serializer.Context);
  895. return newObject;
  896. }
  897. #endif
  898. private object CreateObjectFromNonDefaultConstructor(JsonReader reader, JsonObjectContract contract, JsonProperty containerProperty, ConstructorInfo constructorInfo, string id)
  899. {
  900. ValidationUtils.ArgumentNotNull(constructorInfo, "constructorInfo");
  901. Type objectType = contract.UnderlyingType;
  902. IDictionary<JsonProperty, object> propertyValues = ResolvePropertyAndConstructorValues(contract, containerProperty, reader, objectType);
  903. IDictionary<ParameterInfo, object> constructorParameters = constructorInfo.GetParameters().ToDictionary(p => p, p => (object) null);
  904. IDictionary<JsonProperty, object> remainingPropertyValues = new Dictionary<JsonProperty, object>();
  905. foreach (KeyValuePair<JsonProperty, object> propertyValue in propertyValues)
  906. {
  907. ParameterInfo matchingConstructorParameter = constructorParameters.ForgivingCaseSensitiveFind(kv => kv.Key.Name, propertyValue.Key.UnderlyingName).Key;
  908. if (matchingConstructorParameter != null)
  909. constructorParameters[matchingConstructorParameter] = propertyValue.Value;
  910. else
  911. remainingPropertyValues.Add(propertyValue);
  912. }
  913. object createdObject = constructorInfo.Invoke(constructorParameters.Values.ToArray());
  914. if (id != null)
  915. Serializer.ReferenceResolver.AddReference(this, id, createdObject);
  916. contract.InvokeOnDeserializing(createdObject, Serializer.Context);
  917. // go through unused values and set the newly created object's properties
  918. foreach (KeyValuePair<JsonProperty, object> remainingPropertyValue in remainingPropertyValues)
  919. {
  920. JsonProperty property = remainingPropertyValue.Key;
  921. object value = remainingPropertyValue.Value;
  922. if (ShouldSetPropertyValue(remainingPropertyValue.Key, remainingPropertyValue.Value))
  923. {
  924. property.ValueProvider.SetValue(createdObject, value);
  925. }
  926. else if (!property.Writable && value != null)
  927. {
  928. // handle readonly collection/dictionary properties
  929. JsonContract propertyContract = Serializer.ContractResolver.ResolveContract(property.PropertyType);
  930. if (propertyContract.ContractType == JsonContractType.Array)
  931. {
  932. JsonArrayContract propertyArrayContract = (JsonArrayContract)propertyContract;
  933. object createdObjectCollection = property.ValueProvider.GetValue(createdObject);
  934. if (createdObjectCollection != null)
  935. {
  936. IWrappedCollection createdObjectCollectionWrapper = propertyArrayContract.CreateWrapper(createdObjectCollection);
  937. IWrappedCollection newValues = propertyArrayContract.CreateWrapper(value);
  938. foreach (object newValue in newValues)
  939. {
  940. createdObjectCollectionWrapper.Add(newValue);
  941. }
  942. }
  943. }
  944. else if (propertyContract.ContractType == JsonContractType.Dictionary)
  945. {
  946. JsonDictionaryContract jsonDictionaryContract = (JsonDictionaryContract)propertyContract;
  947. object createdObjectDictionary = property.ValueProvider.GetValue(createdObject);
  948. if (createdObjectDictionary != null)
  949. {
  950. IWrappedDictionary createdObjectDictionaryWrapper = jsonDictionaryContract.CreateWrapper(createdObjectDictionary);
  951. IWrappedDictionary newValues = jsonDictionaryContract.CreateWrapper(value);
  952. foreach (DictionaryEntry newValue in newValues)
  953. {
  954. createdObjectDictionaryWrapper.Add(newValue.Key, newValue.Value);
  955. }
  956. }
  957. }
  958. }
  959. }
  960. contract.InvokeOnDeserialized(createdObject, Serializer.Context);
  961. return createdObject;
  962. }
  963. private IDictionary<JsonProperty, object> ResolvePropertyAndConstructorValues(JsonObjectContract contract, JsonProperty containerProperty, JsonReader reader, Type objectType)
  964. {
  965. IDictionary<JsonProperty, object> propertyValues = new Dictionary<JsonProperty, object>();
  966. bool exit = false;
  967. do
  968. {
  969. switch (reader.TokenType)
  970. {
  971. case JsonToken.PropertyName:
  972. string memberName = reader.Value.ToString();
  973. // attempt exact case match first
  974. // then try match ignoring case
  975. JsonProperty property = contract.ConstructorParameters.GetClosestMatchProperty(memberName) ??
  976. contract.Properties.GetClosestMatchProperty(memberName);
  977. if (property != null)
  978. {
  979. if (property.PropertyContract == null)
  980. property.PropertyContract = GetContractSafe(property.PropertyType);
  981. JsonConverter propertyConverter = GetConverter(property.PropertyContract, property.MemberConverter, contract, containerProperty);
  982. if (!ReadForType(reader, property.PropertyContract, propertyConverter != null))
  983. throw JsonSerializationException.Create(reader, "Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName));
  984. if (!property.Ignored)
  985. {
  986. if (property.PropertyContract == null)
  987. property.PropertyContract = GetContractSafe(property.PropertyType);
  988. object propertyValue;
  989. if (propertyConverter != null && propertyConverter.CanRead)
  990. propertyValue = propertyConverter.ReadJson(reader, property.PropertyType, null, GetInternalSerializer());
  991. else
  992. propertyValue = CreateValueInternal(reader, property.PropertyType, property.PropertyContract, property, contract, containerProperty, null);
  993. propertyValues[property] = propertyValue;
  994. }
  995. else
  996. {
  997. reader.Skip();
  998. }
  999. }
  1000. else
  1001. {
  1002. if (!reader.Read())
  1003. throw JsonSerializationException.Create(reader, "Unexpected end w…

Large files files are truncated, but you can click here to view the full file