我有稳定的web-api解决方案,我正在使用HttpWebRequest从MVC控制器访问api方法。 GET和POST在没有Date Time对象的情况下工作正常。但是当从web api返回的数据有Date时我得到的错误
"反序列化Contracts.AppointmentInfo []类型的对象时出错。日期时间内容' 2014-09-18T11:00:00'不以' /日期开头('并以'结尾)/'根据JSON"
的要求
我已经搞过这个链接了 DataContractJsonSerializer - Deserializing DateTime within List<object> 但它们指的是转换对象列表,但在我的情况下,我有来自HttpWebRequest的响应。
这是我的代码,inputSerializer输入到web api方法并且工作正常,但outputSerializer失败,因为它在结果集中有DateTime。
var request = (HttpWebRequest)HttpWebRequest.Create(endpoint);
request.Accept = "application/json";
request.ContentType = "application/json";
request.Method = method;
var inputSerializer = new DataContractJsonSerializer(typeof(T));
var outputSerializer = new DataContractJsonSerializer(typeof(T[]));
var requestStream = request.GetRequestStream();
inputSerializer.WriteObject(requestStream, pun);
requestStream.Close();
var response = request.GetResponse();
if (response.ContentLength == 0)
{
response.Close();
return default(T[]);
}
var responseStream = response.GetResponseStream();
var responseObject = (T[])outputSerializer.ReadObject(responseStream);
responseStream.Close();
return responseObject;
我也试过从HttpWebRequest读取响应,如下所示,但不起作用
byte[] bytes = new byte[response.ContentLength];
responseStream.Read(bytes, 0, bytes.Length);
string output = Encoding.ASCII.GetString(bytes);
和输出字符串就像这样
[{\"id\":190,\"CalendarId\":1,\"CustomerId\":52,\"AppointmentDate\":\"2014-09-18T11:00:00\",\"start\":\"2014-09-18T11:00:00\",\"end\":\"2014-09-18T12:30:00\"
解决
我做了以下改变及其工作
Stream resstream = response.GetResponseStream();
int count = 0;
do
{
count = resstream.Read(buf, 0, buf.Length);
if (count != 0)
{
tempString = Encoding.ASCII.GetString(buf, 0, count);
sb.Append(tempString);
}
}
while (count > 0);
{
Response.Write(sb.ToString() + "<br/><br/>");
}
JavaScriptSerializer ser = new JavaScriptSerializer();
T[] responseObject = ser.Deserialize<T[]>(sb.ToString());