Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialize Json Object - DateTime

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 string that would represent the DateTime isn't valid it's missing \Date ...

{System.Runtime.Serialization.SerializationException: There was an error deserializing the object of type User. DateTime content '1984-10-02T01:00:00' does not start with '/Date(' and end 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 i use to deserialize.

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;
        }
    }
like image 585
Sam_vdd Avatar asked Dec 26 '12 16:12

Sam_vdd


1 Answers

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.

like image 79
theMayer Avatar answered Oct 19 '22 11:10

theMayer