I am using the Facebook Graph API which is returning a a json object that contains a datetime in a string in the following format: “created_time”: “2013-01-25T00:11:02+0000”
The deserialized object contains this datetime: “0001-01-01 00:00:00”, which I suppose is the equivalent of null. How can I deserialize the datetime string properly?
Here is my DTO class:
using System;
using System.ComponentModel;
using System.Runtime.Serialization;
using System.Text.Json.Serialization;
using Newtonsoft.Json.Converters;
using project.DTOs;
namespace project.DTOs.Facebook
{
public class FacebookCommentResponseDto
{
[JsonPropertyName("id")]
public string Id { get; set; }
[JsonPropertyName("from")]
public FacebookUserDto From { get; set; }
[JsonPropertyName("message")]
public string Message { get; set; }
[JsonPropertyName("created_time")]
[JsonConverter(typeof(CustomDateTimeConverter))]
public DateTime CreatedTime { get; set;}
}
internal class CustomDateTimeConverter : IsoDateTimeConverter
{
public CustomDateTimeConverter()
{
base.DateTimeFormat = "yyyy-MM-ddTH:mm:ss.fffK";
}
}
}
This is the code where I deserialize the object:
var result = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<T>(result);
2
Answers
In your code you have
using Newtonsoft.Json.Converters;
andusing System.Text.Json.Serialization;
. OnFacebookCommentResponseDto
you useJsonPropertyName
which belongs toSystem.Text
but the converter classCustomDateTimeConverter
is meant to be used with theNewtonsoft.Json
attributeJsonProperty
not with theSystem.Text
attributeJsonPropertyName
. Hence in your code the converter is never called.One solution ist to remove
using System.Text.Json.Serialization;
and replaceJsonPropertyName
inFacebookCommentResponseDto
withJsonProperty
. That means you only useNewtonsoft.Json
and then the date conversion even works out-of-the-box without a converter. The following test is green:As Marius said,your converter is for Newtonsoft while attributes are for
System.Text.Json
.You could change[JsonPropertyName]
to[JsonProperty]
.Another solution is to custom converter which implements
JsonConverter<DateTime>
inSystem.Text.Json
:1.Converter:
2.Deserialize: