PDA

View Full Version : JSONP - Getting json from Web API



rashidawan
28 Jul 2015, 7:34 AM
Not sure if any one of you come across to this problem. I am requesting json from my view to load data in my store. The request is going to a ASP.NET web api and of a type jsonp due to cross domain.

My web api is returning json with escape characters which is unrecognized by the proxy. A sample json is as per below.

"Ext.data.JsonP.callback1({
\"items\": [
{
\"headerid\": 1,
\"headerdesc\": \"SubTotal1\",
\"code\": \"LABOUR\",
\"description\": \"some thing\",
\"value\": 42.0
}
]
})

Not sure if I should resolve this within my webservice or is there a resolution within sencha api.

mitchellsimoens
30 Jul 2015, 6:47 AM
What you return has to be valid JavaScript. The way JsonP works is it creates a <script> and when that <script> loads it executes the function that is wrapping your actual Json data, in this case it'd be Ext.data.JsonP.callback1. Ext JS creates that function so when it executes, it tells the proxy the load has finished. What you have there is not valid JavaScript because of the quote escaping.

rashidawan
30 Jul 2015, 7:33 AM
Thanks for your reply. I resolved the issue by removing the escape characters from the returned json. For anyone, who may be interested in how to return pure json from ASP.NET web api, the C# sample code below may of interest. The code is for .NET framework 4.0.




String returnContent = "";
String callBack = Utilities.GetQueryString(requestMessage, "callback");
HttpContent serializeJson = new JsonContent(new d(returnValue));
returnContent = serializeJson.ReadAsStringAsync().Result;
if (!String.IsNullOrEmpty(callBack)) {
returnContent = callBack + "(" + returnContent + ")";
}
return new HttpResponseMessage()
{
Content = new StringContent(returnContent)
};


The code for JsonContent



public class JsonContent : HttpContent
{
private readonly MemoryStream _Stream = new MemoryStream();


public JsonContent(object value)
{
Headers.ContentType = new MediaTypeHeaderValue("application/json");
var jw = new JsonTextWriter(new StreamWriter(_Stream));
//jw.Formatting = Formatting.Indented;
var serializer = new JsonSerializer();
serializer.Serialize(jw, value);
jw.Flush();
_Stream.Position = 0;
}


protected override Task SerializeToStreamAsync(Stream stream,
TransportContext context)
{
_Stream.WriteTo(stream);
var tcs = new TaskCompletionSource<object>();
tcs.SetResult(null);
return tcs.Task;
}


protected override bool TryComputeLength(out long length)
{
length = -1;
return false;
}
}

mitchellsimoens
30 Jul 2015, 7:34 AM
You may want to use the [CODE]...[/CODE} when posting code.

rashidawan
30 Jul 2015, 7:37 AM
Edited the post thanks.