/// <summary> /// Reads the JSON representation of the object. /// </summary> /// <param name="reader">The <see cref="JsonReader"/> to read from.</param> /// <param name="objectType">Type of the object.</param> /// <param name="existingValue">The existing property value of the JSON that is being converted.</param> /// <param name="serializer">The calling serializer.</param> /// <returns>The object value.</returns> public override object?ReadJson(JsonReader reader, Type objectType, object?existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null) { if (!ReflectionUtils.IsNullable(objectType)) { throw JsonSerializationException.Create(reader, "Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType)); } return(null); } if (reader.TokenType != JsonToken.StartConstructor || !string.Equals(reader.Value?.ToString(), "Date", StringComparison.Ordinal)) { throw JsonSerializationException.Create(reader, "Unexpected token or value when parsing date. Token: {0}, Value: {1}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType, reader.Value)); } if (!JavaScriptUtils.TryGetDateFromConstructorJson(reader, out DateTime d, out string?errorMessage)) { throw JsonSerializationException.Create(reader, errorMessage); } #if HAVE_DATE_TIME_OFFSET Type t = (ReflectionUtils.IsNullableType(objectType)) ? Nullable.GetUnderlyingType(objectType) : objectType; if (t == typeof(DateTimeOffset)) { return(new DateTimeOffset(d)); } #endif return(d); }
public override object ReadJson(JsonReader reader, Type objectType, [Nullable(2)] object existingValue, JsonSerializer serializer) { if (reader.TokenType != JsonToken.Null) { if (reader.TokenType == JsonToken.StartConstructor) { object value = reader.Value; if (string.Equals((value != null) ? value.ToString() : null, "Date", StringComparison.Ordinal)) { DateTime dateTime; string message; if (!JavaScriptUtils.TryGetDateFromConstructorJson(reader, out dateTime, out message)) { throw JsonSerializationException.Create(reader, message); } if ((ReflectionUtils.IsNullableType(objectType) ? Nullable.GetUnderlyingType(objectType) : objectType) == typeof(DateTimeOffset)) { return new DateTimeOffset(dateTime); } return dateTime; } } throw JsonSerializationException.Create(reader, "Unexpected token or value when parsing date. Token: {0}, Value: {1}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType, reader.Value)); } if (!ReflectionUtils.IsNullable(objectType)) { throw JsonSerializationException.Create(reader, "Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType)); } return null; }