2

I have a WebAPI set up which is accepting JSON, using the Newtonsoft.Json package, where one of the fields is a DateTime.

In order to avoid problems with invalid or ambiguous date formats, I only want to accept specific date formats on the input.

For example, only accept:

var validFormats = new string[]
{
    "yyyy-MM-ddTHH:mm:ss",           // 2009-06-15T13:45:30
    "yyyy-MM-ddTHH:mm:ss.fffffffzz", // 2009-06-15T13:45:30.0000000-07:00
};

The problem I am having is that wherever I try to do any manual format validation or parsing, it seems that the parser has already deserialised and converted the string to a DateTime object, so I cannot get hold of the date in the original format to check.

What is the best way to accomplish this?

Update 1:

The closest I have come is to use a custom converter:

public class JsonDateTimeConverter : DateTimeConverterBase
{
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var validFormats = new string[]
        {
            "yyyy-MM-ddTHH:mm:ss",           // 2009-06-15T13:45:30
            "yyyy-MM-ddTHH:mm:ss.fffffffzz", // 2009-06-15T13:45:30.0000000-07:00
        };

        DateTime dt;
        if (DateTime.TryParseExact(reader.Value.ToString(), validFormats, null, DateTimeStyles.None, out dt))
        {
            return dt;
        }

        throw new JsonException("Failed to parse DateTime");
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        writer.WriteValue(((DateTime)value).ToString("o"));
    }
}

Configured to be used in the WebApiConfig as

config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new JsonDateTimeConverter());

But this still has the issue where the reader.value appears to already have been converted to a DateTime object. There is a private member on JsonReader called _stringReference which appears to contain the original string, but I am unable to access this in within the converter.

DBPaul
  • 500
  • 5
  • 16

1 Answers1

0

According to:

Foy's answer from here: https://stackoverflow.com/a/37441177/2711861

var dateTimeConverter = new IsoDateTimeConverter { DateTimeFormat = "dd/MM/yyyy" };
myObject obj = JsonConvert.DeserializeObject<myObject>(myJSONString, dateTimeConverter);
Community
  • 1
  • 1
DLL_Whisperer
  • 815
  • 9
  • 22
  • If an answer is close enough you could just quote an answer from another question you should have likely just voted to close the question as a duplicate instead. – Scott Chamberlain Apr 24 '17 at 14:47
  • Unfortunately this isn't sufficient for JSON coming in on a WebAPI, as the serialization is done automatically. I don't know where I would need to use JsonConvert manually on the WebAPI request? – DBPaul Apr 24 '17 at 14:58