简体   繁体   English

.NET Core - 转换读取JSON文件的日期

[英].NET Core - converting date of read JSON file

is there any way to convert date read from JSON file? 有没有办法转换从JSON文件读取的日期? Exemplary record from my file is: 我文件中的示例记录是:

{
    "UserID": 73274,
    "Created": "17-03-2018 06:35",
    "Office": "Washington"
},

What I am doing is importing JSON file and save its content to database. 我正在做的是导入JSON文件并将其内容保存到数据库。 The problem is, when date is in DD-MM-YYYY hh:ss format, it simply doesn't work. 问题是,当日期是DD-MM-YYYY hh:ss格式时,它根本不起作用。 But when date is in YYYY-MM-DDThh:mm:ss format, everything is fine. 但是当日期是YYYY-MM-DDThh:mm:ss格式时,一切都很好。 How to parse date to another format after reading this file and execute following operations on file with parsed date? 如何在读取此文件后将日期解析为另一种格式,并在具有解析日期的文件上执行以下操作?

Part of my controller responsible for this operations is: 负责此操作的部分控制器是:

if (file.ContentType == "application/json")
{
    try
    {
        using (var reader = new StreamReader(file.OpenReadStream()))
        {
            content = reader.ReadToEnd();
        }
     }
     catch
     {
         return BadRequest(Messages.fileNotChosen);
     }
     try
     {
         userObjects = JsonConvert.DeserializeObject<List<UserImportModel>>(content);
     }
     catch
     {
         return BadRequest();
     }
 }

When date format is YYYY-MM-DDThh:mm:ss , userObjects is properly counted and controller moves to part where I execute adding to database. 当日期格式为YYYY-MM-DDThh:mm:ss ,userObjects被正确计数,控制器移动到我执行添加到数据库的部分。 When date format is DD-MM-YYYY hh:ss , userObjects = 0 and controller moves to catch, which then returns BadRequest(). 当日期格式为DD-MM-YYYY hh:ss ,userObjects = 0并且控制器移动到catch,然后返回BadRequest()。

EDIT: Code of UserImportModel class: 编辑: UserImportModel类的代码:

public class UserImportModel
{

    public string UserID { get; set; }

    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
    public DateTime Created { get; set; }

    public string Office { get; set; }

}

If you need to deserialize date in different formats, you have to create a custom JsonConverter : 如果需要以不同格式反序列化日期,则必须创建自定义JsonConverter

public class MultiFormatDateTimeConverter : JsonConverter
{
    private List<string> formats;

    public MultiFormatDateTimeConverter(List<string> formats)
    {
       this.formats = formats;
    }

    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(DateTime);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        string dateString = (string)reader.Value;

        foreach (string format in formats)
        {
            if (DateTime.TryParseExact(dateString, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime date))
            {
                return date;
            }
        }
        throw new JsonException("Unable to parse \"" + dateString + "\" as a date.");
    }

    public override bool CanWrite
    {
        get { return false; }
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

Usage example: 用法示例:

var settings = new JsonSerializerSettings();
settings.DateParseHandling = DateParseHandling.None;
settings.Converters.Add(new MultiFormatDateTimeConverter(new List<string> { "DD-MM-YYYY hh:ss", "YYYY-MM-DDThh:mm:ss" }));

userObjects = JsonConvert.DeserializeObject<List<UserImportModel>>(content, settings);

JSON.Net uses the Standard 8601 to represent Date-Time . JSON.Net使用标准8601来表示日期时间 The extended format for a complete date-time expression is: "YYYY-MM-DDTHH:MM:SS". 完整日期时间表达式的扩展格式为:“YYYY-MM-DDTHH:MM:SS”。 The JSON.Net "Deserializer" method ( DeserializeObject ) is overloaded for acceptting custom formatters, you can use de IsoDateTimeConverter specifying in the DateTimeFormat property the format of your string "dd" JSON.Net“Deserializer”方法( DeserializeObject )重载以接受自定义格式化程序,您可以使用de IsoDateTimeConverterDateTimeFormat属性中指定字符串“dd”的格式

userObjects = JsonConvert.DeserializeObject<List<UserImportModel>>(content, 
                   new IsoDateTimeConverter { DateTimeFormat = "dd-MM-yyyy hh:mm:ss" });

Another alternative is to use a regular expresion to replace all bad formed ISO Dates in your JSON string before calling the DeserializeObject method . 另一种方法是在调用DeserializeObject方法之前使用常规表达式替换JSON字符串中所有错误形成的ISO日期

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM