I have stable web-api solution and I am accessing api methods from MVC controller using HttpWebRequest. GET and POST working fine without Date Time object.But when data returned from web api has Date then I am getting below error
"There was an error deserializing the object of type Contracts.AppointmentInfo[]. DateTime content '2014-09-18T11:00:00' does not start with '/Date(' and end with ')/' as required for JSON"
I haved chcked this link DataContractJsonSerializer - Deserializing DateTime within List<object> but they refer to converting List of objects, but in my case I have Response from HttpWebRequest.
Here is my code , inputSerializer is input to web api method and works fine, but outputSerializer fails because it has DateTime in the resultset.
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 have also tried to read response from HttpWebRequest as below, but does not work
byte[] bytes = new byte[response.ContentLength];
responseStream.Read(bytes, 0, bytes.Length);
string output = Encoding.ASCII.GetString(bytes);
and output string came like this
[{\"id\":190,\"CalendarId\":1,\"CustomerId\":52,\"AppointmentDate\":\"2014-09-18T11:00:00\",\"start\":\"2014-09-18T11:00:00\",\"end\":\"2014-09-18T12:30:00\"
Resolved
I have made below change and its working
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());