Deserialize Json Object - DateTime

My web-api returns a user object. This object has a DateTime property. When I read it in my application, I get an error because the string that will represent DateTime is invalid, it is missing \Date ...

{System.Runtime.Serialization.SerializationException: There is an error deserializing an object of type User. The content of DateTime '1984-10-02T01: 00: 00' does not start with '/ Date (' and ends with ') /' as required for JSON. --->

 public static async Task<User> GetUser(string email) { try { using (HttpClient client = new HttpClient()) { HttpResponseMessage response = await client.GetAsync(url + "?email="+email); if (response.IsSuccessStatusCode) { string content = await response.Content.ReadAsStringAsync(); User user = DataService.Deserialize<User>(content); return user; } return null; } } catch (Exception ex) { return null; } } 

This is the method that I use for deserialization.

 public static T Deserialize<T>(string json) { try { var _Bytes = Encoding.Unicode.GetBytes(json); using (MemoryStream _Stream = new MemoryStream(_Bytes)) { var _Serializer = new DataContractJsonSerializer(typeof(T)); return (T)_Serializer.ReadObject(_Stream); } } catch (Exception ex) { throw ex; } } 
+5
source share
6 answers

I found how to fix this when adding the Json.net package (Newtonsoft.Json).

 public async static Task<T> Deserialize<T>(string json) { var value = await Newtonsoft.Json.JsonConvert.DeserializeObjectAsync<T>(json); return value; } 
+7
source

To get around this, perhaps the easiest way is to set the value type in your DataContract type to "string". Then, if you need to work with .NET datetime, you will need to do DateTime.Parse on your string value. This will eliminate the problem of deserialization. It is likely that for the original class that was serialized, a string value was used first, as there is no necessary formatting for dates.

Please note that when you do 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.

+9
source

There is no standard format for exchanging dates in the JSON specification , so there are so many different heterogeneous date formats in JSON!

DataContractJsonSerializer serializing a date in millisecond format since 1970, surrounded by Date() like this: Date(1335205592410) and expects the same format to be deserialized to DateTime . However, what you get as a JSON date string is the ISO8601 format, the format of which in most browsers / software today is used to serialize dates!

JavaScriptSerializer is an alternative JSON serializer in .Net that can pretty much serialize any type, including anonymous types or from a JSON string, and is capable of deserializing JSON dates in either the ISO8601 format or the DataContractJsonSerializer format.

Using JavaScriptSerializer , your Deserialize method will look like this:

 public static T Deserialize<T>(string json) { return new JavaScriptSerializer().Deserialize<T>(json); } 
+8
source

Could it be that the DateTime really returns as "nullable", for example, "DateTime?". (with a question mark)?

Because then it can be NULL, like ".HasValue == false".

Just guess here ... :-)

+1
source

Just change the DateTimeFormat to your DataContractJsonSerializer as follows:

  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; } } 
+1
source

@theMayer: I tried the solution you proposed, i.e. β€œTo get around this, perhaps the easiest way is to set the value type in your DataContract type toβ€œ string. ”Then, if you need to work with .NET datetime, you will need to make DateTime.Parse on your string value. This will fix your the deserialization problem.Probably, for the original class that was serialized, a string value was used first, as there is no necessary formatting for dates.

Please note that when you do 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. "

But I got this error: String was not recognized as a valid DateTime. , Date and time format: / Date (1544007801877-0600) /, and then I do Datetime.Parse on it.

0
source

Source: https://habr.com/ru/post/1203246/


All Articles