且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

反序列化JSON对象 - 日期时间

更新时间:2023-02-16 15:38:28

我。发现如何将包Json.net(Newtonsoft.Json)时修复它。

 公共异步静态任务< T>反序列化< T>(JSON字符串)
{
VAR值=等待Newtonsoft.Json.JsonConvert.DeserializeObjectAsync< T>(JSON);
返回值;
}


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;
        }
    }

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;
    }