我需要同时期待: dd / MM / yyyy 和 dd / MM / yyyy HH:mm:ss
var dateTimeConverter = new IsoDateTimeConverter { DateTimeFormat = "dd/MM/yyyy HH:mm:ss" };
var resultado = JsonConvert.DeserializeObject<MyObject>(json, dateTimeConverter);
使用此代码,我收到以下错误消息:
System.FormatException:'字符串未被识别为有效的DateTime。'
答案 0 :(得分:4)
您根本不需要指定任何转换器。默认情况下,这两种格式都可以使用。
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);
答案 1 :(得分:1)
您可以编写自己的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;
}
}
答案 2 :(得分:0)
也许你可以像这样继承IsoDateTimeConverter:
class Format1 : IsoDateTimeConverter
{
public Format1()
{
DateTimeFormat = @"dd/MM/yyyy";
}
}
class Format2 : IsoDateTimeConverter
{
public Format2()
{
DateTimeFormat = @"dd/MM/yyyy HH:mm:ss";
}
}
然后你只需将JsonConverter属性添加到模型中,如下所示:
class Entity
{
[JsonConverter(typeof(Format1))]
public DateTime Date1 { get; set; }