My web-api
returns an User Object. In that object there is a DateTime
property. When i\'am reading it in my Application i get an error because the
Just change the DateTimeFormat on your DataContractJsonSerializer like so:
public static T Deserialize<T>(string json) {
try
{
var settings = new DataContractJsonSerializerSettings
{
DateTimeFormat = new System.Runtime.Serialization.DateTimeFormat("o")
};
var _Bytes = Encoding.Unicode.GetBytes(json);
using (MemoryStream _Stream = new MemoryStream(_Bytes))
{
var _Serializer = new DataContractJsonSerializer(typeof(T), settings);
return (T)_Serializer.ReadObject(_Stream);
}
}
catch (Exception ex)
{
throw ex;
}
}
To get around this, probably the easiest way is to set the value type on your DataContract type to 'string'. Then, if you need to work with .NET datetimes, you will need to do a DateTime.Parse on your string value. This will eliminate your deserialization problem. It's likely that the original class that was serialized used a string value to begin with, since it is missing the required formatting for dates.
Note that when you do a DateTime.Parse, if the time zone information is present, it will convert it to the local time of your computer (this is stupid, I know). Just FYI.
Could it be that the DateTime is actually coming back as a "nullable", like "DateTime?" (with the question mark)?
Because then, it could be NULL, as and ".HasValue == false".
Only guessing here... :-)
I found how to fix it when adding the package Json.net (Newtonsoft.Json).
public async static Task<T> Deserialize<T>(string json)
{
var value = await Newtonsoft.Json.JsonConvert.DeserializeObjectAsync<T>(json);
return value;
}
There's no standard format for exchanging dates in the JSON specification, which is why there are so many different heterogeneous formats of dates in JSON!
DataContractJsonSerializer
serializes date in the format counting msecs since 1970 surrounded by Date()
something like this: Date(1335205592410)
and expects the same format to deserialize back to DateTime
. However what you are getting as a JSON date string is a ISO8601 format which is the format most browsers/softwares today use to serialize dates!
JavaScriptSerializer
is an alternative JSON serializer in .Net which can pretty much serialize any type, including anonymous types to or from JSON string, and it is capable of deserializing JSON dates either in ISO8601 format or the format DataContractJsonSerializer
provides.
Using JavaScriptSerializer
, your Deserialize method would look like this:
public static T Deserialize<T>(string json)
{
return new JavaScriptSerializer().Deserialize<T>(json);
}