我的web-api返回一个用户对象,在该对象中有一个DateTime属性。当我在应用程序中读取它时,会出现错误,因为表示DateTime的字符串无效,缺少\Date...。
{System.Runtime.Serialization.SerializationException:反序列化类型为User的对象时出错。 DateTime内容“1984-10-02T01:00: 00”不以所需的JSON格式“/ Date()”开头和结尾。 --->}
{System.Runtime.Serialization.SerializationException:反序列化类型为User的对象时出错。 DateTime内容“1984-10-02T01:00: 00”不以所需的JSON格式“/ Date()”开头和结尾。 --->}
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;
}
}
这是我用来反序列化的方法。
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;
}
}