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.

1221 lines
50 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;
  27. using System.Collections.Generic;
  28. using System.Diagnostics;
  29. using System.Globalization;
  30. using System.IO;
  31. using System.Runtime.Serialization.Formatters;
  32. using Newtonsoft.Json.Converters;
  33. using Newtonsoft.Json.Serialization;
  34. using Newtonsoft.Json.Utilities;
  35. using System.Runtime.Serialization;
  36. using ErrorEventArgs = Newtonsoft.Json.Serialization.ErrorEventArgs;
  37. namespace Newtonsoft.Json
  38. {
  39. /// <summary>
  40. /// Serializes and deserializes objects into and from the JSON format.
  41. /// The <see cref="JsonSerializer"/> enables you to control how objects are encoded into JSON.
  42. /// </summary>
  43. internal class JsonSerializer
  44. {
  45. internal TypeNameHandling _typeNameHandling;
  46. internal TypeNameAssemblyFormatHandling _typeNameAssemblyFormatHandling;
  47. internal PreserveReferencesHandling _preserveReferencesHandling;
  48. internal ReferenceLoopHandling _referenceLoopHandling;
  49. internal MissingMemberHandling _missingMemberHandling;
  50. internal ObjectCreationHandling _objectCreationHandling;
  51. internal NullValueHandling _nullValueHandling;
  52. internal DefaultValueHandling _defaultValueHandling;
  53. internal ConstructorHandling _constructorHandling;
  54. internal MetadataPropertyHandling _metadataPropertyHandling;
  55. internal JsonConverterCollection _converters;
  56. internal IContractResolver _contractResolver;
  57. internal ITraceWriter _traceWriter;
  58. internal IEqualityComparer _equalityComparer;
  59. internal ISerializationBinder _serializationBinder;
  60. internal StreamingContext _context;
  61. private IReferenceResolver _referenceResolver;
  62. private Formatting? _formatting;
  63. private DateFormatHandling? _dateFormatHandling;
  64. private DateTimeZoneHandling? _dateTimeZoneHandling;
  65. private DateParseHandling? _dateParseHandling;
  66. private FloatFormatHandling? _floatFormatHandling;
  67. private FloatParseHandling? _floatParseHandling;
  68. private StringEscapeHandling? _stringEscapeHandling;
  69. private CultureInfo _culture;
  70. private int? _maxDepth;
  71. private bool _maxDepthSet;
  72. private bool? _checkAdditionalContent;
  73. private string _dateFormatString;
  74. private bool _dateFormatStringSet;
  75. /// <summary>
  76. /// Occurs when the <see cref="JsonSerializer"/> errors during serialization and deserialization.
  77. /// </summary>
  78. public virtual event EventHandler<ErrorEventArgs> Error;
  79. /// <summary>
  80. /// Gets or sets the <see cref="IReferenceResolver"/> used by the serializer when resolving references.
  81. /// </summary>
  82. public virtual IReferenceResolver ReferenceResolver
  83. {
  84. get => GetReferenceResolver();
  85. set
  86. {
  87. if (value == null)
  88. {
  89. throw new ArgumentNullException(nameof(value), "Reference resolver cannot be null.");
  90. }
  91. _referenceResolver = value;
  92. }
  93. }
  94. /// <summary>
  95. /// Gets or sets the <see cref="SerializationBinder"/> used by the serializer when resolving type names.
  96. /// </summary>
  97. [Obsolete("Binder is obsolete. Use SerializationBinder instead.")]
  98. public virtual SerializationBinder Binder
  99. {
  100. get
  101. {
  102. if (_serializationBinder == null)
  103. {
  104. return null;
  105. }
  106. if (_serializationBinder is SerializationBinder legacySerializationBinder)
  107. {
  108. return legacySerializationBinder;
  109. }
  110. if (_serializationBinder is SerializationBinderAdapter adapter)
  111. {
  112. return adapter.SerializationBinder;
  113. }
  114. throw new InvalidOperationException("Cannot get SerializationBinder because an ISerializationBinder was previously set.");
  115. }
  116. set
  117. {
  118. if (value == null)
  119. {
  120. throw new ArgumentNullException(nameof(value), "Serialization binder cannot be null.");
  121. }
  122. _serializationBinder = value as ISerializationBinder ?? new SerializationBinderAdapter(value);
  123. }
  124. }
  125. /// <summary>
  126. /// Gets or sets the <see cref="ISerializationBinder"/> used by the serializer when resolving type names.
  127. /// </summary>
  128. public virtual ISerializationBinder SerializationBinder
  129. {
  130. get => _serializationBinder;
  131. set
  132. {
  133. if (value == null)
  134. {
  135. throw new ArgumentNullException(nameof(value), "Serialization binder cannot be null.");
  136. }
  137. _serializationBinder = value;
  138. }
  139. }
  140. /// <summary>
  141. /// Gets or sets the <see cref="ITraceWriter"/> used by the serializer when writing trace messages.
  142. /// </summary>
  143. /// <value>The trace writer.</value>
  144. public virtual ITraceWriter TraceWriter
  145. {
  146. get => _traceWriter;
  147. set => _traceWriter = value;
  148. }
  149. /// <summary>
  150. /// Gets or sets the equality comparer used by the serializer when comparing references.
  151. /// </summary>
  152. /// <value>The equality comparer.</value>
  153. public virtual IEqualityComparer EqualityComparer
  154. {
  155. get => _equalityComparer;
  156. set => _equalityComparer = value;
  157. }
  158. /// <summary>
  159. /// Gets or sets how type name writing and reading is handled by the serializer.
  160. /// The default value is <see cref="Json.TypeNameHandling.None" />.
  161. /// </summary>
  162. /// <remarks>
  163. /// <see cref="JsonSerializer.TypeNameHandling"/> should be used with caution when your application deserializes JSON from an external source.
  164. /// Incoming types should be validated with a custom <see cref="JsonSerializer.SerializationBinder"/>
  165. /// when deserializing with a value other than <see cref="TypeNameHandling.None"/>.
  166. /// </remarks>
  167. public virtual TypeNameHandling TypeNameHandling
  168. {
  169. get => _typeNameHandling;
  170. set
  171. {
  172. if (value < TypeNameHandling.None || value > TypeNameHandling.Auto)
  173. {
  174. throw new ArgumentOutOfRangeException(nameof(value));
  175. }
  176. _typeNameHandling = value;
  177. }
  178. }
  179. /// <summary>
  180. /// Gets or sets how a type name assembly is written and resolved by the serializer.
  181. /// The default value is <see cref="FormatterAssemblyStyle.Simple" />.
  182. /// </summary>
  183. /// <value>The type name assembly format.</value>
  184. [Obsolete("TypeNameAssemblyFormat is obsolete. Use TypeNameAssemblyFormatHandling instead.")]
  185. public virtual FormatterAssemblyStyle TypeNameAssemblyFormat
  186. {
  187. get => (FormatterAssemblyStyle)_typeNameAssemblyFormatHandling;
  188. set
  189. {
  190. if (value < FormatterAssemblyStyle.Simple || value > FormatterAssemblyStyle.Full)
  191. {
  192. throw new ArgumentOutOfRangeException(nameof(value));
  193. }
  194. _typeNameAssemblyFormatHandling = (TypeNameAssemblyFormatHandling)value;
  195. }
  196. }
  197. /// <summary>
  198. /// Gets or sets how a type name assembly is written and resolved by the serializer.
  199. /// The default value is <see cref="Json.TypeNameAssemblyFormatHandling.Simple" />.
  200. /// </summary>
  201. /// <value>The type name assembly format.</value>
  202. public virtual TypeNameAssemblyFormatHandling TypeNameAssemblyFormatHandling
  203. {
  204. get => _typeNameAssemblyFormatHandling;
  205. set
  206. {
  207. if (value < TypeNameAssemblyFormatHandling.Simple || value > TypeNameAssemblyFormatHandling.Full)
  208. {
  209. throw new ArgumentOutOfRangeException(nameof(value));
  210. }
  211. _typeNameAssemblyFormatHandling = value;
  212. }
  213. }
  214. /// <summary>
  215. /// Gets or sets how object references are preserved by the serializer.
  216. /// The default value is <see cref="Json.PreserveReferencesHandling.None" />.
  217. /// </summary>
  218. public virtual PreserveReferencesHandling PreserveReferencesHandling
  219. {
  220. get => _preserveReferencesHandling;
  221. set
  222. {
  223. if (value < PreserveReferencesHandling.None || value > PreserveReferencesHandling.All)
  224. {
  225. throw new ArgumentOutOfRangeException(nameof(value));
  226. }
  227. _preserveReferencesHandling = value;
  228. }
  229. }
  230. /// <summary>
  231. /// Gets or sets how reference loops (e.g. a class referencing itself) is handled.
  232. /// The default value is <see cref="Json.ReferenceLoopHandling.Error" />.
  233. /// </summary>
  234. public virtual ReferenceLoopHandling ReferenceLoopHandling
  235. {
  236. get => _referenceLoopHandling;
  237. set
  238. {
  239. if (value < ReferenceLoopHandling.Error || value > ReferenceLoopHandling.Serialize)
  240. {
  241. throw new ArgumentOutOfRangeException(nameof(value));
  242. }
  243. _referenceLoopHandling = value;
  244. }
  245. }
  246. /// <summary>
  247. /// Gets or sets how missing members (e.g. JSON contains a property that isn't a member on the object) are handled during deserialization.
  248. /// The default value is <see cref="Json.MissingMemberHandling.Ignore" />.
  249. /// </summary>
  250. public virtual MissingMemberHandling MissingMemberHandling
  251. {
  252. get => _missingMemberHandling;
  253. set
  254. {
  255. if (value < MissingMemberHandling.Ignore || value > MissingMemberHandling.Error)
  256. {
  257. throw new ArgumentOutOfRangeException(nameof(value));
  258. }
  259. _missingMemberHandling = value;
  260. }
  261. }
  262. /// <summary>
  263. /// Gets or sets how null values are handled during serialization and deserialization.
  264. /// The default value is <see cref="Json.NullValueHandling.Include" />.
  265. /// </summary>
  266. public virtual NullValueHandling NullValueHandling
  267. {
  268. get => _nullValueHandling;
  269. set
  270. {
  271. if (value < NullValueHandling.Include || value > NullValueHandling.Ignore)
  272. {
  273. throw new ArgumentOutOfRangeException(nameof(value));
  274. }
  275. _nullValueHandling = value;
  276. }
  277. }
  278. /// <summary>
  279. /// Gets or sets how default values are handled during serialization and deserialization.
  280. /// The default value is <see cref="Json.DefaultValueHandling.Include" />.
  281. /// </summary>
  282. public virtual DefaultValueHandling DefaultValueHandling
  283. {
  284. get => _defaultValueHandling;
  285. set
  286. {
  287. if (value < DefaultValueHandling.Include || value > DefaultValueHandling.IgnoreAndPopulate)
  288. {
  289. throw new ArgumentOutOfRangeException(nameof(value));
  290. }
  291. _defaultValueHandling = value;
  292. }
  293. }
  294. /// <summary>
  295. /// Gets or sets how objects are created during deserialization.
  296. /// The default value is <see cref="Json.ObjectCreationHandling.Auto" />.
  297. /// </summary>
  298. /// <value>The object creation handling.</value>
  299. public virtual ObjectCreationHandling ObjectCreationHandling
  300. {
  301. get => _objectCreationHandling;
  302. set
  303. {
  304. if (value < ObjectCreationHandling.Auto || value > ObjectCreationHandling.Replace)
  305. {
  306. throw new ArgumentOutOfRangeException(nameof(value));
  307. }
  308. _objectCreationHandling = value;
  309. }
  310. }
  311. /// <summary>
  312. /// Gets or sets how constructors are used during deserialization.
  313. /// The default value is <see cref="Json.ConstructorHandling.Default" />.
  314. /// </summary>
  315. /// <value>The constructor handling.</value>
  316. public virtual ConstructorHandling ConstructorHandling
  317. {
  318. get => _constructorHandling;
  319. set
  320. {
  321. if (value < ConstructorHandling.Default || value > ConstructorHandling.AllowNonPublicDefaultConstructor)
  322. {
  323. throw new ArgumentOutOfRangeException(nameof(value));
  324. }
  325. _constructorHandling = value;
  326. }
  327. }
  328. /// <summary>
  329. /// Gets or sets how metadata properties are used during deserialization.
  330. /// The default value is <see cref="Json.MetadataPropertyHandling.Default" />.
  331. /// </summary>
  332. /// <value>The metadata properties handling.</value>
  333. public virtual MetadataPropertyHandling MetadataPropertyHandling
  334. {
  335. get => _metadataPropertyHandling;
  336. set
  337. {
  338. if (value < MetadataPropertyHandling.Default || value > MetadataPropertyHandling.Ignore)
  339. {
  340. throw new ArgumentOutOfRangeException(nameof(value));
  341. }
  342. _metadataPropertyHandling = value;
  343. }
  344. }
  345. /// <summary>
  346. /// Gets a collection <see cref="JsonConverter"/> that will be used during serialization.
  347. /// </summary>
  348. /// <value>Collection <see cref="JsonConverter"/> that will be used during serialization.</value>
  349. public virtual JsonConverterCollection Converters
  350. {
  351. get
  352. {
  353. if (_converters == null)
  354. {
  355. _converters = new JsonConverterCollection();
  356. }
  357. return _converters;
  358. }
  359. }
  360. /// <summary>
  361. /// Gets or sets the contract resolver used by the serializer when
  362. /// serializing .NET objects to JSON and vice versa.
  363. /// </summary>
  364. public virtual IContractResolver ContractResolver
  365. {
  366. get => _contractResolver;
  367. set => _contractResolver = value ?? DefaultContractResolver.Instance;
  368. }
  369. /// <summary>
  370. /// Gets or sets the <see cref="StreamingContext"/> used by the serializer when invoking serialization callback methods.
  371. /// </summary>
  372. /// <value>The context.</value>
  373. public virtual StreamingContext Context
  374. {
  375. get => _context;
  376. set => _context = value;
  377. }
  378. /// <summary>
  379. /// Indicates how JSON text output is formatted.
  380. /// The default value is <see cref="Json.Formatting.None" />.
  381. /// </summary>
  382. public virtual Formatting Formatting
  383. {
  384. get => _formatting ?? JsonSerializerSettings.DefaultFormatting;
  385. set => _formatting = value;
  386. }
  387. /// <summary>
  388. /// Gets or sets how dates are written to JSON text.
  389. /// The default value is <see cref="Json.DateFormatHandling.IsoDateFormat" />.
  390. /// </summary>
  391. public virtual DateFormatHandling DateFormatHandling
  392. {
  393. get => _dateFormatHandling ?? JsonSerializerSettings.DefaultDateFormatHandling;
  394. set => _dateFormatHandling = value;
  395. }
  396. /// <summary>
  397. /// Gets or sets how <see cref="DateTime"/> time zones are handled during serialization and deserialization.
  398. /// The default value is <see cref="Json.DateTimeZoneHandling.RoundtripKind" />.
  399. /// </summary>
  400. public virtual DateTimeZoneHandling DateTimeZoneHandling
  401. {
  402. get => _dateTimeZoneHandling ?? JsonSerializerSettings.DefaultDateTimeZoneHandling;
  403. set => _dateTimeZoneHandling = value;
  404. }
  405. /// <summary>
  406. /// Gets or sets how date formatted strings, e.g. <c>"\/Date(1198908717056)\/"</c> and <c>"2012-03-21T05:40Z"</c>, are parsed when reading JSON.
  407. /// The default value is <see cref="Json.DateParseHandling.DateTime" />.
  408. /// </summary>
  409. public virtual DateParseHandling DateParseHandling
  410. {
  411. get => _dateParseHandling ?? JsonSerializerSettings.DefaultDateParseHandling;
  412. set => _dateParseHandling = value;
  413. }
  414. /// <summary>
  415. /// Gets or sets how floating point numbers, e.g. 1.0 and 9.9, are parsed when reading JSON text.
  416. /// The default value is <see cref="Json.FloatParseHandling.Double" />.
  417. /// </summary>
  418. public virtual FloatParseHandling FloatParseHandling
  419. {
  420. get => _floatParseHandling ?? JsonSerializerSettings.DefaultFloatParseHandling;
  421. set => _floatParseHandling = value;
  422. }
  423. /// <summary>
  424. /// Gets or sets how special floating point numbers, e.g. <see cref="Double.NaN"/>,
  425. /// <see cref="Double.PositiveInfinity"/> and <see cref="Double.NegativeInfinity"/>,
  426. /// are written as JSON text.
  427. /// The default value is <see cref="Json.FloatFormatHandling.String" />.
  428. /// </summary>
  429. public virtual FloatFormatHandling FloatFormatHandling
  430. {
  431. get => _floatFormatHandling ?? JsonSerializerSettings.DefaultFloatFormatHandling;
  432. set => _floatFormatHandling = value;
  433. }
  434. /// <summary>
  435. /// Gets or sets how strings are escaped when writing JSON text.
  436. /// The default value is <see cref="Json.StringEscapeHandling.Default" />.
  437. /// </summary>
  438. public virtual StringEscapeHandling StringEscapeHandling
  439. {
  440. get => _stringEscapeHandling ?? JsonSerializerSettings.DefaultStringEscapeHandling;
  441. set => _stringEscapeHandling = value;
  442. }
  443. /// <summary>
  444. /// Gets or sets how <see cref="DateTime"/> and <see cref="DateTimeOffset"/> values are formatted when writing JSON text,
  445. /// and the expected date format when reading JSON text.
  446. /// The default value is <c>"yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK"</c>.
  447. /// </summary>
  448. public virtual string DateFormatString
  449. {
  450. get => _dateFormatString ?? JsonSerializerSettings.DefaultDateFormatString;
  451. set
  452. {
  453. _dateFormatString = value;
  454. _dateFormatStringSet = true;
  455. }
  456. }
  457. /// <summary>
  458. /// Gets or sets the culture used when reading JSON.
  459. /// The default value is <see cref="CultureInfo.InvariantCulture"/>.
  460. /// </summary>
  461. public virtual CultureInfo Culture
  462. {
  463. get => _culture ?? JsonSerializerSettings.DefaultCulture;
  464. set => _culture = value;
  465. }
  466. /// <summary>
  467. /// Gets or sets the maximum depth allowed when reading JSON. Reading past this depth will throw a <see cref="JsonReaderException"/>.
  468. /// A null value means there is no maximum.
  469. /// The default value is <c>null</c>.
  470. /// </summary>
  471. public virtual int? MaxDepth
  472. {
  473. get => _maxDepth;
  474. set
  475. {
  476. if (value <= 0)
  477. {
  478. throw new ArgumentException("Value must be positive.", nameof(value));
  479. }
  480. _maxDepth = value;
  481. _maxDepthSet = true;
  482. }
  483. }
  484. /// <summary>
  485. /// Gets a value indicating whether there will be a check for additional JSON content after deserializing an object.
  486. /// The default value is <c>false</c>.
  487. /// </summary>
  488. /// <value>
  489. /// <c>true</c> if there will be a check for additional JSON content after deserializing an object; otherwise, <c>false</c>.
  490. /// </value>
  491. public virtual bool CheckAdditionalContent
  492. {
  493. get => _checkAdditionalContent ?? JsonSerializerSettings.DefaultCheckAdditionalContent;
  494. set => _checkAdditionalContent = value;
  495. }
  496. internal bool IsCheckAdditionalContentSet()
  497. {
  498. return (_checkAdditionalContent != null);
  499. }
  500. /// <summary>
  501. /// Initializes a new instance of the <see cref="JsonSerializer"/> class.
  502. /// </summary>
  503. public JsonSerializer()
  504. {
  505. _referenceLoopHandling = JsonSerializerSettings.DefaultReferenceLoopHandling;
  506. _missingMemberHandling = JsonSerializerSettings.DefaultMissingMemberHandling;
  507. _nullValueHandling = JsonSerializerSettings.DefaultNullValueHandling;
  508. _defaultValueHandling = JsonSerializerSettings.DefaultDefaultValueHandling;
  509. _objectCreationHandling = JsonSerializerSettings.DefaultObjectCreationHandling;
  510. _preserveReferencesHandling = JsonSerializerSettings.DefaultPreserveReferencesHandling;
  511. _constructorHandling = JsonSerializerSettings.DefaultConstructorHandling;
  512. _typeNameHandling = JsonSerializerSettings.DefaultTypeNameHandling;
  513. _metadataPropertyHandling = JsonSerializerSettings.DefaultMetadataPropertyHandling;
  514. _context = JsonSerializerSettings.DefaultContext;
  515. _serializationBinder = DefaultSerializationBinder.Instance;
  516. _culture = JsonSerializerSettings.DefaultCulture;
  517. _contractResolver = DefaultContractResolver.Instance;
  518. }
  519. /// <summary>
  520. /// Creates a new <see cref="JsonSerializer"/> instance.
  521. /// The <see cref="JsonSerializer"/> will not use default settings
  522. /// from <see cref="JsonConvert.DefaultSettings"/>.
  523. /// </summary>
  524. /// <returns>
  525. /// A new <see cref="JsonSerializer"/> instance.
  526. /// The <see cref="JsonSerializer"/> will not use default settings
  527. /// from <see cref="JsonConvert.DefaultSettings"/>.
  528. /// </returns>
  529. public static JsonSerializer Create()
  530. {
  531. return new JsonSerializer();
  532. }
  533. /// <summary>
  534. /// Creates a new <see cref="JsonSerializer"/> instance using the specified <see cref="JsonSerializerSettings"/>.
  535. /// The <see cref="JsonSerializer"/> will not use default settings
  536. /// from <see cref="JsonConvert.DefaultSettings"/>.
  537. /// </summary>
  538. /// <param name="settings">The settings to be applied to the <see cref="JsonSerializer"/>.</param>
  539. /// <returns>
  540. /// A new <see cref="JsonSerializer"/> instance using the specified <see cref="JsonSerializerSettings"/>.
  541. /// The <see cref="JsonSerializer"/> will not use default settings
  542. /// from <see cref="JsonConvert.DefaultSettings"/>.
  543. /// </returns>
  544. public static JsonSerializer Create(JsonSerializerSettings settings)
  545. {
  546. JsonSerializer serializer = Create();
  547. if (settings != null)
  548. {
  549. ApplySerializerSettings(serializer, settings);
  550. }
  551. return serializer;
  552. }
  553. /// <summary>
  554. /// Creates a new <see cref="JsonSerializer"/> instance.
  555. /// The <see cref="JsonSerializer"/> will use default settings
  556. /// from <see cref="JsonConvert.DefaultSettings"/>.
  557. /// </summary>
  558. /// <returns>
  559. /// A new <see cref="JsonSerializer"/> instance.
  560. /// The <see cref="JsonSerializer"/> will use default settings
  561. /// from <see cref="JsonConvert.DefaultSettings"/>.
  562. /// </returns>
  563. public static JsonSerializer CreateDefault()
  564. {
  565. // copy static to local variable to avoid concurrency issues
  566. JsonSerializerSettings defaultSettings = JsonConvert.DefaultSettings?.Invoke();
  567. return Create(defaultSettings);
  568. }
  569. /// <summary>
  570. /// Creates a new <see cref="JsonSerializer"/> instance using the specified <see cref="JsonSerializerSettings"/>.
  571. /// The <see cref="JsonSerializer"/> will use default settings
  572. /// from <see cref="JsonConvert.DefaultSettings"/> as well as the specified <see cref="JsonSerializerSettings"/>.
  573. /// </summary>
  574. /// <param name="settings">The settings to be applied to the <see cref="JsonSerializer"/>.</param>
  575. /// <returns>
  576. /// A new <see cref="JsonSerializer"/> instance using the specified <see cref="JsonSerializerSettings"/>.
  577. /// The <see cref="JsonSerializer"/> will use default settings
  578. /// from <see cref="JsonConvert.DefaultSettings"/> as well as the specified <see cref="JsonSerializerSettings"/>.
  579. /// </returns>
  580. public static JsonSerializer CreateDefault(JsonSerializerSettings settings)
  581. {
  582. JsonSerializer serializer = CreateDefault();
  583. if (settings != null)
  584. {
  585. ApplySerializerSettings(serializer, settings);
  586. }
  587. return serializer;
  588. }
  589. private static void ApplySerializerSettings(JsonSerializer serializer, JsonSerializerSettings settings)
  590. {
  591. if (!CollectionUtils.IsNullOrEmpty(settings.Converters))
  592. {
  593. // insert settings converters at the beginning so they take precedence
  594. // if user wants to remove one of the default converters they will have to do it manually
  595. for (int i = 0; i < settings.Converters.Count; i++)
  596. {
  597. serializer.Converters.Insert(i, settings.Converters[i]);
  598. }
  599. }
  600. // serializer specific
  601. if (settings._typeNameHandling != null)
  602. {
  603. serializer.TypeNameHandling = settings.TypeNameHandling;
  604. }
  605. if (settings._metadataPropertyHandling != null)
  606. {
  607. serializer.MetadataPropertyHandling = settings.MetadataPropertyHandling;
  608. }
  609. if (settings._typeNameAssemblyFormatHandling != null)
  610. {
  611. serializer.TypeNameAssemblyFormatHandling = settings.TypeNameAssemblyFormatHandling;
  612. }
  613. if (settings._preserveReferencesHandling != null)
  614. {
  615. serializer.PreserveReferencesHandling = settings.PreserveReferencesHandling;
  616. }
  617. if (settings._referenceLoopHandling != null)
  618. {
  619. serializer.ReferenceLoopHandling = settings.ReferenceLoopHandling;
  620. }
  621. if (settings._missingMemberHandling != null)
  622. {
  623. serializer.MissingMemberHandling = settings.MissingMemberHandling;
  624. }
  625. if (settings._objectCreationHandling != null)
  626. {
  627. serializer.ObjectCreationHandling = settings.ObjectCreationHandling;
  628. }
  629. if (settings._nullValueHandling != null)
  630. {
  631. serializer.NullValueHandling = settings.NullValueHandling;
  632. }
  633. if (settings._defaultValueHandling != null)
  634. {
  635. serializer.DefaultValueHandling = settings.DefaultValueHandling;
  636. }
  637. if (settings._constructorHandling != null)
  638. {
  639. serializer.ConstructorHandling = settings.ConstructorHandling;
  640. }
  641. if (settings._context != null)
  642. {
  643. serializer.Context = settings.Context;
  644. }
  645. if (settings._checkAdditionalContent != null)
  646. {
  647. serializer._checkAdditionalContent = settings._checkAdditionalContent;
  648. }
  649. if (settings.Error != null)
  650. {
  651. serializer.Error += settings.Error;
  652. }
  653. if (settings.ContractResolver != null)
  654. {
  655. serializer.ContractResolver = settings.ContractResolver;
  656. }
  657. if (settings.ReferenceResolverProvider != null)
  658. {
  659. serializer.ReferenceResolver = settings.ReferenceResolverProvider();
  660. }
  661. if (settings.TraceWriter != null)
  662. {
  663. serializer.TraceWriter = settings.TraceWriter;
  664. }
  665. if (settings.EqualityComparer != null)
  666. {
  667. serializer.EqualityComparer = settings.EqualityComparer;
  668. }
  669. if (settings.SerializationBinder != null)
  670. {
  671. serializer.SerializationBinder = settings.SerializationBinder;
  672. }
  673. // reader/writer specific
  674. // unset values won't override reader/writer set values
  675. if (settings._formatting != null)
  676. {
  677. serializer._formatting = settings._formatting;
  678. }
  679. if (settings._dateFormatHandling != null)
  680. {
  681. serializer._dateFormatHandling = settings._dateFormatHandling;
  682. }
  683. if (settings._dateTimeZoneHandling != null)
  684. {
  685. serializer._dateTimeZoneHandling = settings._dateTimeZoneHandling;
  686. }
  687. if (settings._dateParseHandling != null)
  688. {
  689. serializer._dateParseHandling = settings._dateParseHandling;
  690. }
  691. if (settings._dateFormatStringSet)
  692. {
  693. serializer._dateFormatString = settings._dateFormatString;
  694. serializer._dateFormatStringSet = settings._dateFormatStringSet;
  695. }
  696. if (settings._floatFormatHandling != null)
  697. {
  698. serializer._floatFormatHandling = settings._floatFormatHandling;
  699. }
  700. if (settings._floatParseHandling != null)
  701. {
  702. serializer._floatParseHandling = settings._floatParseHandling;
  703. }
  704. if (settings._stringEscapeHandling != null)
  705. {
  706. serializer._stringEscapeHandling = settings._stringEscapeHandling;
  707. }
  708. if (settings._culture != null)
  709. {
  710. serializer._culture = settings._culture;
  711. }
  712. if (settings._maxDepthSet)
  713. {
  714. serializer._maxDepth = settings._maxDepth;
  715. serializer._maxDepthSet = settings._maxDepthSet;
  716. }
  717. }
  718. /// <summary>
  719. /// Populates the JSON values onto the target object.
  720. /// </summary>
  721. /// <param name="reader">The <see cref="TextReader"/> that contains the JSON structure to reader values from.</param>
  722. /// <param name="target">The target object to populate values onto.</param>
  723. public void Populate(TextReader reader, object target)
  724. {
  725. Populate(new JsonTextReader(reader), target);
  726. }
  727. /// <summary>
  728. /// Populates the JSON values onto the target object.
  729. /// </summary>
  730. /// <param name="reader">The <see cref="JsonReader"/> that contains the JSON structure to reader values from.</param>
  731. /// <param name="target">The target object to populate values onto.</param>
  732. public void Populate(JsonReader reader, object target)
  733. {
  734. PopulateInternal(reader, target);
  735. }
  736. internal virtual void PopulateInternal(JsonReader reader, object target)
  737. {
  738. ValidationUtils.ArgumentNotNull(reader, nameof(reader));
  739. ValidationUtils.ArgumentNotNull(target, nameof(target));
  740. // set serialization options onto reader
  741. CultureInfo previousCulture;
  742. DateTimeZoneHandling? previousDateTimeZoneHandling;
  743. DateParseHandling? previousDateParseHandling;
  744. FloatParseHandling? previousFloatParseHandling;
  745. int? previousMaxDepth;
  746. string previousDateFormatString;
  747. SetupReader(reader, out previousCulture, out previousDateTimeZoneHandling, out previousDateParseHandling, out previousFloatParseHandling, out previousMaxDepth, out previousDateFormatString);
  748. TraceJsonReader traceJsonReader = (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
  749. ? CreateTraceJsonReader(reader)
  750. : null;
  751. JsonSerializerInternalReader serializerReader = new JsonSerializerInternalReader(this);
  752. serializerReader.Populate(traceJsonReader ?? reader, target);
  753. if (traceJsonReader != null)
  754. {
  755. TraceWriter.Trace(TraceLevel.Verbose, traceJsonReader.GetDeserializedJsonMessage(), null);
  756. }
  757. ResetReader(reader, previousCulture, previousDateTimeZoneHandling, previousDateParseHandling, previousFloatParseHandling, previousMaxDepth, previousDateFormatString);
  758. }
  759. /// <summary>
  760. /// Deserializes the JSON structure contained by the specified <see cref="JsonReader"/>.
  761. /// </summary>
  762. /// <param name="reader">The <see cref="JsonReader"/> that contains the JSON structure to deserialize.</param>
  763. /// <returns>The <see cref="Object"/> being deserialized.</returns>
  764. public object Deserialize(JsonReader reader)
  765. {
  766. return Deserialize(reader, null);
  767. }
  768. /// <summary>
  769. /// Deserializes the JSON structure contained by the specified <see cref="StringReader"/>
  770. /// into an instance of the specified type.
  771. /// </summary>
  772. /// <param name="reader">The <see cref="TextReader"/> containing the object.</param>
  773. /// <param name="objectType">The <see cref="Type"/> of object being deserialized.</param>
  774. /// <returns>The instance of <paramref name="objectType"/> being deserialized.</returns>
  775. public object Deserialize(TextReader reader, Type objectType)
  776. {
  777. return Deserialize(new JsonTextReader(reader), objectType);
  778. }
  779. /// <summary>
  780. /// Deserializes the JSON structure contained by the specified <see cref="JsonReader"/>
  781. /// into an instance of the specified type.
  782. /// </summary>
  783. /// <param name="reader">The <see cref="JsonReader"/> containing the object.</param>
  784. /// <typeparam name="T">The type of the object to deserialize.</typeparam>
  785. /// <returns>The instance of <typeparamref name="T"/> being deserialized.</returns>
  786. public T Deserialize<T>(JsonReader reader)
  787. {
  788. return (T)Deserialize(reader, typeof(T));
  789. }
  790. /// <summary>
  791. /// Deserializes the JSON structure contained by the specified <see cref="JsonReader"/>
  792. /// into an instance of the specified type.
  793. /// </summary>
  794. /// <param name="reader">The <see cref="JsonReader"/> containing the object.</param>
  795. /// <param name="objectType">The <see cref="Type"/> of object being deserialized.</param>
  796. /// <returns>The instance of <paramref name="objectType"/> being deserialized.</returns>
  797. public object Deserialize(JsonReader reader, Type objectType)
  798. {
  799. return DeserializeInternal(reader, objectType);
  800. }
  801. internal virtual object DeserializeInternal(JsonReader reader, Type objectType)
  802. {
  803. ValidationUtils.ArgumentNotNull(reader, nameof(reader));
  804. // set serialization options onto reader
  805. CultureInfo previousCulture;
  806. DateTimeZoneHandling? previousDateTimeZoneHandling;
  807. DateParseHandling? previousDateParseHandling;
  808. FloatParseHandling? previousFloatParseHandling;
  809. int? previousMaxDepth;
  810. string previousDateFormatString;
  811. SetupReader(reader, out previousCulture, out previousDateTimeZoneHandling, out previousDateParseHandling, out previousFloatParseHandling, out previousMaxDepth, out previousDateFormatString);
  812. TraceJsonReader traceJsonReader = (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
  813. ? CreateTraceJsonReader(reader)
  814. : null;
  815. JsonSerializerInternalReader serializerReader = new JsonSerializerInternalReader(this);
  816. object value = serializerReader.Deserialize(traceJsonReader ?? reader, objectType, CheckAdditionalContent);
  817. if (traceJsonReader != null)
  818. {
  819. TraceWriter.Trace(TraceLevel.Verbose, traceJsonReader.GetDeserializedJsonMessage(), null);
  820. }
  821. ResetReader(reader, previousCulture, previousDateTimeZoneHandling, previousDateParseHandling, previousFloatParseHandling, previousMaxDepth, previousDateFormatString);
  822. return value;
  823. }
  824. private void SetupReader(JsonReader reader, out CultureInfo previousCulture, out DateTimeZoneHandling? previousDateTimeZoneHandling, out DateParseHandling? previousDateParseHandling, out FloatParseHandling? previousFloatParseHandling, out int? previousMaxDepth, out string previousDateFormatString)
  825. {
  826. if (_culture != null && !_culture.Equals(reader.Culture))
  827. {
  828. previousCulture = reader.Culture;
  829. reader.Culture = _culture;
  830. }
  831. else
  832. {
  833. previousCulture = null;
  834. }
  835. if (_dateTimeZoneHandling != null && reader.DateTimeZoneHandling != _dateTimeZoneHandling)
  836. {
  837. previousDateTimeZoneHandling = reader.DateTimeZoneHandling;
  838. reader.DateTimeZoneHandling = _dateTimeZoneHandling.GetValueOrDefault();
  839. }
  840. else
  841. {
  842. previousDateTimeZoneHandling = null;
  843. }
  844. if (_dateParseHandling != null && reader.DateParseHandling != _dateParseHandling)
  845. {
  846. previousDateParseHandling = reader.DateParseHandling;
  847. reader.DateParseHandling = _dateParseHandling.GetValueOrDefault();
  848. }
  849. else
  850. {
  851. previousDateParseHandling = null;
  852. }
  853. if (_floatParseHandling != null && reader.FloatParseHandling != _floatParseHandling)
  854. {
  855. previousFloatParseHandling = reader.FloatParseHandling;
  856. reader.FloatParseHandling = _floatParseHandling.GetValueOrDefault();
  857. }
  858. else
  859. {
  860. previousFloatParseHandling = null;
  861. }
  862. if (_maxDepthSet && reader.MaxDepth != _maxDepth)
  863. {
  864. previousMaxDepth = reader.MaxDepth;
  865. reader.MaxDepth = _maxDepth;
  866. }
  867. else
  868. {
  869. previousMaxDepth = null;
  870. }
  871. if (_dateFormatStringSet && reader.DateFormatString != _dateFormatString)
  872. {
  873. previousDateFormatString = reader.DateFormatString;
  874. reader.DateFormatString = _dateFormatString;
  875. }
  876. else
  877. {
  878. previousDateFormatString = null;
  879. }
  880. if (reader is JsonTextReader textReader)
  881. {
  882. if (_contractResolver is DefaultContractResolver resolver)
  883. {
  884. textReader.NameTable = resolver.GetNameTable();
  885. }
  886. }
  887. }
  888. private void ResetReader(JsonReader reader, CultureInfo previousCulture, DateTimeZoneHandling? previousDateTimeZoneHandling, DateParseHandling? previousDateParseHandling, FloatParseHandling? previousFloatParseHandling, int? previousMaxDepth, string previousDateFormatString)
  889. {
  890. // reset reader back to previous options
  891. if (previousCulture != null)
  892. {
  893. reader.Culture = previousCulture;
  894. }
  895. if (previousDateTimeZoneHandling != null)
  896. {
  897. reader.DateTimeZoneHandling = previousDateTimeZoneHandling.GetValueOrDefault();
  898. }
  899. if (previousDateParseHandling != null)
  900. {
  901. reader.DateParseHandling = previousDateParseHandling.GetValueOrDefault();
  902. }
  903. if (previousFloatParseHandling != null)
  904. {
  905. reader.FloatParseHandling = previousFloatParseHandling.GetValueOrDefault();
  906. }
  907. if (_maxDepthSet)
  908. {
  909. reader.MaxDepth = previousMaxDepth;
  910. }
  911. if (_dateFormatStringSet)
  912. {
  913. reader.DateFormatString = previousDateFormatString;
  914. }
  915. if (reader is JsonTextReader textReader)
  916. {
  917. textReader.NameTable = null;
  918. }
  919. }
  920. /// <summary>
  921. /// Serializes the specified <see cref="Object"/> and writes the JSON structure
  922. /// using the specified <see cref="TextWriter"/>.
  923. /// </summary>
  924. /// <param name="textWriter">The <see cref="TextWriter"/> used to write the JSON structure.</param>
  925. /// <param name="value">The <see cref="Object"/> to serialize.</param>
  926. public void Serialize(TextWriter textWriter, object value)
  927. {
  928. Serialize(new JsonTextWriter(textWriter), value);
  929. }
  930. /// <summary>
  931. /// Serializes the specified <see cref="Object"/> and writes the JSON structure
  932. /// using the specified <see cref="JsonWriter"/>.
  933. /// </summary>
  934. /// <param name="jsonWriter">The <see cref="JsonWriter"/> used to write the JSON structure.</param>
  935. /// <param name="value">The <see cref="Object"/> to serialize.</param>
  936. /// <param name="objectType">
  937. /// The type of the value being serialized.
  938. /// This parameter is used when <see cref="JsonSerializer.TypeNameHandling"/> is <see cref="Json.TypeNameHandling.Auto"/> to write out the type name if the type of the value does not match.
  939. /// Specifying the type is optional.
  940. /// </param>
  941. public void Serialize(JsonWriter jsonWriter, object value, Type objectType)
  942. {
  943. SerializeInternal(jsonWriter, value, objectType);
  944. }
  945. /// <summary>
  946. /// Serializes the specified <see cref="Object"/> and writes the JSON structure
  947. /// using the specified <see cref="TextWriter"/>.
  948. /// </summary>
  949. /// <param name="textWriter">The <see cref="TextWriter"/> used to write the JSON structure.</param>
  950. /// <param name="value">The <see cref="Object"/> to serialize.</param>
  951. /// <param name="objectType">
  952. /// The type of the value being serialized.
  953. /// This parameter is used when <see cref="TypeNameHandling"/> is Auto to write out the type name if the type of the value does not match.
  954. /// Specifying the type is optional.
  955. /// </param>
  956. public void Serialize(TextWriter textWriter, object value, Type objectType)
  957. {
  958. Serialize(new JsonTextWriter(textWriter), value, objectType);
  959. }
  960. /// <summary>
  961. /// Serializes the specified <see cref="Object"/> and writes the JSON structure
  962. /// using the specified <see cref="JsonWriter"/>.
  963. /// </summary>
  964. /// <param name="jsonWriter">The <see cref="JsonWriter"/> used to write the JSON structure.</param>
  965. /// <param name="value">The <see cref="Object"/> to serialize.</param>
  966. public void Serialize(JsonWriter jsonWriter, object value)
  967. {
  968. SerializeInternal(jsonWriter, value, null);
  969. }
  970. private TraceJsonReader CreateTraceJsonReader(JsonReader reader)
  971. {
  972. TraceJsonReader traceReader = new TraceJsonReader(reader);
  973. if (reader.TokenType != JsonToken.None)
  974. {
  975. traceReader.WriteCurrentToken();
  976. }
  977. return traceReader;
  978. }
  979. internal virtual void SerializeInternal(JsonWriter jsonWriter, object value, Type objectType)
  980. {
  981. ValidationUtils.ArgumentNotNull(jsonWriter, nameof(jsonWriter));
  982. // set serialization options onto writer
  983. Formatting? previousFormatting = null;
  984. if (_formatting != null && jsonWriter.Formatting != _formatting)
  985. {
  986. previousFormatting = jsonWriter.Formatting;
  987. jsonWriter.Formatting = _formatting.GetValueOrDefault();
  988. }
  989. DateFormatHandling? previousDateFormatHandling = null;
  990. if (_dateFormatHandling != null && jsonWriter.DateFormatHandling != _dateFormatHandling)
  991. {
  992. previousDateFormatHandling = jsonWriter.DateFormatHandling;
  993. jsonWriter.DateFormatHandling = _dateFormatHandling.GetValueOrDefault();
  994. }
  995. DateTimeZoneHandling? previousDateTimeZoneHandling = null;
  996. if (_dateTimeZoneHandling != null && jsonWriter.DateTimeZoneHandling != _dateTimeZoneHandling)
  997. {
  998. previousDateTimeZoneHandling = jsonWriter.DateTimeZoneHandling;
  999. jsonWriter.DateTimeZoneHandling = _dateTimeZoneHandling.GetValueOrDefault();
  1000. }
  1001. FloatFormatHandling? previousFloatFormatHandling = null;
  1002. if (_floatFormatHandling != null && jsonWriter.FloatFormatHandling != _floatFormatHandling)
  1003. {
  1004. previousFloatFormatHandling = jsonWriter.FloatFormatHandling;
  1005. jsonWriter.FloatFormatHandling = _floatFormatHandling.GetValueOrDefault();
  1006. }
  1007. StringEscapeHandling? previousStringEscapeHandling = null;
  1008. if (_stringEscapeHandling != null && jsonWriter.StringEscapeHandling != _stringEscapeHandling)
  1009. {
  1010. previousStringEscapeHandling = jsonWriter.StringEscapeHandling;
  1011. jsonWriter.StringEscapeHandling = _stringEscapeHandling.GetValueOrDefault();
  1012. }
  1013. CultureInfo previousCulture = null;
  1014. if (_culture != null && !_culture.Equals(jsonWriter.Culture))
  1015. {
  1016. previousCulture = jsonWriter.Culture;
  1017. jsonWriter.Culture = _culture;
  1018. }
  1019. string previousDateFormatString = null;
  1020. if (_dateFormatStringSet && jsonWriter.DateFormatString != _dateFormatString)
  1021. {
  1022. previousDateFormatString = jsonWriter.DateFormatString;
  1023. jsonWriter.DateFormatString = _dateFormatString;
  1024. }
  1025. TraceJsonWriter traceJsonWriter = (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
  1026. ? new TraceJsonWriter(jsonWriter)
  1027. : null;
  1028. JsonSerializerInternalWriter serializerWriter = new JsonSerializerInternalWriter(this);
  1029. serializerWriter.Serialize(traceJsonWriter ?? jsonWriter, value, objectType);
  1030. if (traceJsonWriter != null)
  1031. {
  1032. TraceWriter.Trace(TraceLevel.Verbose, traceJsonWriter.GetSerializedJsonMessage(), null);
  1033. }
  1034. // reset writer back to previous options
  1035. if (previousFormatting != null)
  1036. {
  1037. jsonWriter.Formatting = previousFormatting.GetValueOrDefault();
  1038. }
  1039. if (previousDateFormatHandling != null)
  1040. {
  1041. jsonWriter.DateFormatHandling = previousDateFormatHandling.GetValueOrDefault();
  1042. }
  1043. if (previousDateTimeZoneHandling != null)
  1044. {
  1045. jsonWriter.DateTimeZoneHandling = previousDateTimeZoneHandling.GetValueOrDefault();
  1046. }
  1047. if (previousFloatFormatHandling != null)
  1048. {
  1049. jsonWriter.FloatFormatHandling = previousFloatFormatHandling.GetValueOrDefault();
  1050. }
  1051. if (previousStringEscapeHandling != null)
  1052. {
  1053. jsonWriter.StringEscapeHandling = previousStringEscapeHandling.GetValueOrDefault();
  1054. }
  1055. if (_dateFormatStringSet)
  1056. {
  1057. jsonWriter.DateFormatString = previousDateFormatString;
  1058. }
  1059. if (previousCulture != null)
  1060. {
  1061. jsonWriter.Culture = previousCulture;
  1062. }
  1063. }
  1064. internal IReferenceResolver GetReferenceResolver()
  1065. {
  1066. if (_referenceResolver == null)
  1067. {
  1068. _referenceResolver = new DefaultReferenceResolver();
  1069. }
  1070. return _referenceResolver;
  1071. }
  1072. internal JsonConverter GetMatchingConverter(Type type)
  1073. {
  1074. return GetMatchingConverter(_converters, type);
  1075. }
  1076. internal static JsonConverter GetMatchingConverter(IList<JsonConverter> converters, Type objectType)
  1077. {
  1078. #if DEBUG
  1079. ValidationUtils.ArgumentNotNull(objectType, nameof(objectType));
  1080. #endif
  1081. if (converters != null)
  1082. {
  1083. for (int i = 0; i < converters.Count; i++)
  1084. {
  1085. JsonConverter converter = converters[i];
  1086. if (converter.CanConvert(objectType))
  1087. {
  1088. return converter;
  1089. }
  1090. }
  1091. }
  1092. return null;
  1093. }
  1094. internal void OnError(ErrorEventArgs e)
  1095. {
  1096. Error?.Invoke(this, e);
  1097. }
  1098. }
  1099. }