I have a stable web-api solution, and I am accessing the api methods from the MVC controller using HttpWebRequest. GET and POST work fine without a Date Time object. But when the data returned from the web api has a Date, then I get below the error
"Error deserializing an object of type Contracts.AppointmentInfo []. The content of DateTime '2014-09-18T11: 00: 00' does not start with '/ Date (' and ends with ') /' as necessary for JSON"
I put this link DataContractJsonSerializer - DateTime deserialization in the <object> list, but they relate to transforming the list of objects, but in my case I have an answer from HttpWebRequest.
Here is my code, inputSerializer is injected into the web api method and works fine, but outputSerializer fails because it has a DateTime in the result set.
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;
I also tried to read the answer from HttpWebRequest as below, but not working
byte[] bytes = new byte[response.ContentLength]; responseStream.Read(bytes, 0, bytes.Length); string output = Encoding.ASCII.GetString(bytes);
and the output line appeared as follows
[{\"id\":190,\"CalendarId\":1,\"CustomerId\":52,\"AppointmentDate\":\"2014-09-18T11:00:00\",\"start\":\"2014-09-18T11:00:00\",\"end\":\"2014-09-18T12:30:00\"
Decided
I made the change below and its work
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());