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

前端 未结 4 2241
灰色年华
灰色年华 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 19:06

    You can create a custom date class that inherits the IsoDateTimeConverter and pass a format on the constructor. On the attributes, you can specify which format corresponds to each property. See code below:

    public class LoginResponse
    {
        [JsonProperty("access_token")]
        public string AccessToken { get; set; }
        [JsonProperty("token_type")]
        public string TokenType { get; set; }
        [JsonProperty("expires_in")]
        public DateTime ExpiresIn { get; set; }
        [JsonProperty("userName")]
        public string Username { get; set; }
        [JsonConverter(typeof(CustomDateFormat), "EEE, dd MMM yyyy HH:mm:ss zzz")]
        [JsonProperty(".issued")]
        public DateTime Issued { get; set; }
        [JsonConverter(typeof(CustomDateFormat), "MMMM dd, yyyy")]
        [JsonProperty(".expires")]
        public DateTime Expires { get; set; }
    }
    
    public class CustomDateFormat : IsoDateTimeConverter
    {
        public CustomDateFormat(string format)
        {
            DateTimeFormat = format;
        }
    }
    

提交回复
热议问题