// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
namespace Microsoft.Graph
{
using System;
using Newtonsoft.Json;
///
/// The Date Converter.
///
public class DateConverter : JsonConverter
{
///
/// Check if the given object can be converted into a Date.
///
/// The type of the object.
/// True if the object is a Date type.
public override bool CanConvert(Type objectType)
{
if (objectType == typeof(Date))
{
return true;
}
return false;
}
///
/// Converts the JSON object into a Date object
///
/// The to read from.
/// The object type.
/// The existing value.
/// The serializer to convert the object with.
///
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
try
{
var dateTime = (DateTime)serializer.Deserialize(reader, typeof(DateTime));
return new Date(dateTime);
}
catch (JsonSerializationException serializationException)
{
throw new ServiceException(
new Error
{
Code = ErrorConstants.Codes.GeneralException,
Message = ErrorConstants.Messages.UnableToDeserializeDate,
},
serializationException);
}
}
///
/// Writes the JSON representation of the object.
///
/// The to write to.
/// The value.
/// The calling serializer.
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var date = value as Date;
if (date != null)
{
writer.WriteValue(date.ToString());
}
else
{
throw new ServiceException(
new Error
{
Code = ErrorConstants.Codes.GeneralException,
Message = ErrorConstants.Messages.InvalidTypeForDateConverter,
});
}
}
}
}