I have an ASP.NET webservice method that returns a generics list (List'<'Construct>) serialized as JSON, using code such as this:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class TestService : System.Web.Services.WebService {
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetOccupationListJSON(int SOCLevel)
{
Construct NewConstructList = new ConstructList();
DataContractJsonSerializer serializer = new DataContractJsonSerializer(ConstructList.GetType());
MemoryStream ms = new MemoryStream();
serializer.WriteObject(ms, NewConstructList);
string json = Encoding.Default.GetString(ms.ToArray());
return json;
}
}
I then use jQuery to call this method, and get the JSON data, like so:
function GetCustomerList() {
$.ajax({
type: "POST",
url: "/WebService.asmx/GetConstructList",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) { LoadConstructData(data.d); },
failure: function() { alert("Sorry, we were unable to find the constructs."); }
});
}
The JSON result looks like this:
[
{
"ConstructLabel": "Construct label 1",
"ConstructType": 2,
},
{
"ConstructLabel": "Construct label 2",
"ConstructType": 3,
}
]
I then want to iterate through the elements in the ConstructList in the JSON data. This is the function that gets called on when the jQuery Ajax call is successful:
function LoadConstructData(data) {
for (var i = 0, len = data.length; i < len; ++i) {
var Construct = data[i];
var ConstructLabel = Construct.ConstructLabel
var ConstructType = Construct.ConstructType;
}
}
I assumed (from looking elsewhere) that accessing the JSON data through the index would provide me with access to the underlying object at that index, so that I can then work with it to access its properties.
However, when i=0 and I do var Construct = data[i]; I get the character at the i position of the data array ([), and in the next iteration I get the second character ({). So clearly I am accessing the elements of a string array rather than the JSON data object.
How do I make sure that the data returned by the webservice gets into proper JSON format, so that I can iterate through the object elements within it?