Serializing multiple DateTime properties in the same class using different formats for each one

前端 未结 4 2239
灰色年华
灰色年华 2020-12-01 18:33

I have a class with two DateTime properties. I need to serialize each of the properties with a different format. How can I do it? I tried:

JsonConvert.Serial         


        
4条回答
  •  一向
    一向 (楼主)
    2020-12-01 18:56

    I realise this is an old question, but I stumbled upon it during my search for same question.

    Newtonsoft has now a DateFormatString property in JsonSerializerSettings class which you can use. I came to this question looking for answer and have just found the property, I have used it as below and it works as below:

        private const string _StrDateFormat = "yyyy-MM-dd HH:mm:ss";
    
        private static string GetJSON(object value)
        {
    
            return JsonConvert.SerializeObject(value, new JsonSerializerSettings
            {
                DateFormatString = _StrDateFormat
            });
        }
    

    When value will have a DateTime object, it will convert it into string respecting _StrDateFormat string.

    Perhaps this official link can be updated?

    Regards.

提交回复
热议问题