PDA

View Full Version : JSON Data changes while transferring from C#



MikeandIke
10 Jun 2014, 7:15 AM
When transferring JSON data from a Webmethod in asp.net C# through an Ajax call in ExtJS 4.2.2, several characters are added to the beginning and end of the string.


JSON Data before leaving C#:



[{"ID":"0","NAME":"ALAN"},{"ID":"1","NAME":"BLAKE"}]


JSON Data as seen by firebug which is received by ExtJS



{"d":"[{"ID":"0","NAME":"ALAN"},{"ID":"1","NAME":"BLAKE"}]"}


This will also happen if the JSON Data has a set root property.
From what it appears it seems as if something somewhere along the line treated the incoming data as a variable in a JSON string or something like that.


Code on the C# end:



[WebService(Namespace = "localhost")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class Director : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true, XmlSerializeString = false)]
public string getData()
{
string json = "[{\"ID\":\"0\",\"NAME\":\"ALAN\"},{\"ID\":\"1\",\"NAME\":\"BLAKE\"}]";
System.Diagnostics.Debug.WriteLine(json);
return json;
}
}


Code for the ExtJS Ajax Call (already has a workaround implemented):



Ext.Ajax.request({
async: false,
url: Test061014.ApplicationPath + '/Director.asmx/getData',
headers: { 'Content-Type': 'application/json' },
scope: this,
success: function (conn, response, options, eOpt) {
var s = conn.responseText;
s = s.substring(6, (s.length - 2));
s = s.replace(/\\/g, "");
categoryData = JSON.parse(s);
},
});

cmeans
10 Jun 2014, 6:18 PM
.NET is doing this (for you). It's Microsoft's way of avoiding a remote service from sending down potentially executable script (that it shouldn't).

If you look at my response to your earlier request, you'll see that I've taken the "d" property into account.

-Chris

MikeandIke
10 Jun 2014, 8:23 PM
Thanks, this is the answer I was looking for, and I should have been handling the "d" in my other post as I was able to deal with it. I was just curious as to the reason behind it. Thanks for the response.