Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
263 views
in Technique[技术] by (71.8m points)

c# - 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;
        }
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...