コード例 #1
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var jsonValue = serializer.Deserialize <JValue>(reader);

            switch (jsonValue.Type)
            {
            case JTokenType.Integer:
                var dto = DateTimeOffsetHelper.FromUnixTimeSeconds(jsonValue.Value <long>());
                if (objectType == DateTimeOffsetType || (objectType.IsNullable() && Nullable.GetUnderlyingType(objectType) == DateTimeOffsetType))
                {
                    return(dto);
                }
                return(dto.LocalDateTime);

            case JTokenType.Date:
                if (objectType == DateTimeOffsetType || (objectType.IsNullable() && Nullable.GetUnderlyingType(objectType) == DateTimeOffsetType))
                {
                    return(jsonValue.Value <DateTimeOffset>());
                }
                return(jsonValue.Value <DateTime>());

            case JTokenType.Null:
                if (objectType.IsNullable())
                {
                    return(null);
                }
                throw new JsonSerializationException($"Can't deserialize null value to non-nullable type");

            default:
                throw new JsonSerializationException($"Unexpected token {jsonValue.Type} when parsing a date.");
            }
        }