Reputation: 1969
I need to expect both: dd/MM/yyyy and dd/MM/yyyy HH:mm:ss
var dateTimeConverter = new IsoDateTimeConverter { DateTimeFormat = "dd/MM/yyyy HH:mm:ss" };
var resultado = JsonConvert.DeserializeObject<MyObject>(json, dateTimeConverter);
With this code, i received the following error message:
System.FormatException: 'String was not recognized as a valid DateTime.'
Upvotes: 1
Views: 4311
Reputation: 607
You can write your own JsonConverter:
class DataObject
{
public DateTime CreatedDate { get; set; }
}
class CustomJsonConverter : JsonConverter
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var obj = new DataObject();
reader.Read();
var prop = obj.GetType().GetProperty("CreatedDate");
reader.Read();
var strDate = (string)reader.Value;
DateTime date;
if (DateTime.TryParseExact(strDate, "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
prop.SetValue(obj, date);
if (DateTime.TryParseExact(strDate, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
prop.SetValue(obj, date);
return obj;
}
}
Upvotes: 1
Reputation: 6007
Maybe you could subclass IsoDateTimeConverter like this:
class Format1 : IsoDateTimeConverter
{
public Format1()
{
DateTimeFormat = @"dd/MM/yyyy";
}
}
class Format2 : IsoDateTimeConverter
{
public Format2()
{
DateTimeFormat = @"dd/MM/yyyy HH:mm:ss";
}
}
And then you just add JsonConverter attributes to your model, like this:
class Entity
{
[JsonConverter(typeof(Format1))]
public DateTime Date1 { get; set; }
Upvotes: 0
Reputation: 241525
You don't need to specify any converter at all. By default, both of those formats will work.
class Foo
{
public DateTime DateTime { get; set; }
}
// This Just Works.
string json1 = "{ \"DateTime\" : \"12/31/2017\" }";
string json2 = "{ \"DateTime\" : \"12/31/2017 23:59:59\" }";
var o1 = JsonConvert.DeserializeObject<Foo>(json1);
var o2 = JsonConvert.DeserializeObject<Foo>(json2);
Upvotes: 4