| | 1 | | // Copyright (c) Microsoft Corporation. All rights reserved. |
| | 2 | | // Licensed under the MIT License. See License.txt in the project root for |
| | 3 | | // license information. |
| | 4 | |
|
| | 5 | | using System; |
| | 6 | | using System.Reflection; |
| | 7 | | using Newtonsoft.Json; |
| | 8 | |
|
| | 9 | | namespace Microsoft.Azure.Search.Serialization |
| | 10 | | { |
| | 11 | | /// <summary> |
| | 12 | | /// Converts between dates serialized in ISO 8601 format in JSON strings and <c cref="System.DateTime">System.DateTi |
| | 13 | | /// </summary> |
| | 14 | | /// <remarks> |
| | 15 | | /// This JSON converter ensures that <c cref="System.DateTime">System.DateTime</c> instances are serialized to have |
| | 16 | | /// explicitly included in the JSON. It also ensures that any time zone information in the JSON is taken into accoun |
| | 17 | | /// deserializing to a new <c cref="System.DateTime">System.DateTime</c> instance. For example, if the JSON value's |
| | 18 | | /// is noon and its time zone is UTC-8, the deserialized <c cref="System.DateTime">System.DateTime</c> instance's ti |
| | 19 | | /// and its <c cref="System.DateTime.Kind">Kind</c> will be <c cref="System.DateTimeKind.Utc">DateTimeKind.Utc</c>. |
| | 20 | | /// </remarks> |
| | 21 | | internal class Iso8601DateTimeConverter : JsonConverter |
| | 22 | | { |
| | 23 | | public override bool CanConvert(Type objectType) |
| | 24 | | { |
| 265438 | 25 | | TypeInfo objectTypeInfo = objectType.GetTypeInfo(); |
| 265438 | 26 | | return |
| 265438 | 27 | | typeof(DateTime).GetTypeInfo().IsAssignableFrom(objectTypeInfo) || |
| 265438 | 28 | | typeof(DateTime?).GetTypeInfo().IsAssignableFrom(objectTypeInfo); |
| | 29 | | } |
| | 30 | |
|
| | 31 | | public override object ReadJson( |
| | 32 | | JsonReader reader, |
| | 33 | | Type objectType, |
| | 34 | | object existingValue, |
| | 35 | | JsonSerializer serializer) |
| | 36 | | { |
| | 37 | | // Check for null first. |
| 56 | 38 | | if (reader.TokenType == JsonToken.Null) |
| | 39 | | { |
| 8 | 40 | | return null; |
| | 41 | | } |
| | 42 | |
|
| 48 | 43 | | DateTimeOffset? dateTimeOffset = reader.Expect<DateTimeOffset?>(JsonToken.Date); |
| 48 | 44 | | return dateTimeOffset.HasValue ? dateTimeOffset.Value.UtcDateTime : (DateTime?)null; |
| | 45 | | } |
| | 46 | |
|
| | 47 | | public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) |
| | 48 | | { |
| 56 | 49 | | var dateTime = (DateTime)value; |
| | 50 | |
|
| 56 | 51 | | var dateTimeOffset = |
| 56 | 52 | | dateTime.Kind == DateTimeKind.Unspecified ? |
| 56 | 53 | | new DateTimeOffset(dateTime, TimeSpan.Zero) : |
| 56 | 54 | | new DateTimeOffset(dateTime); |
| | 55 | |
|
| 56 | 56 | | serializer.Serialize(writer, dateTimeOffset); |
| 56 | 57 | | } |
| | 58 | | } |
| | 59 | | } |