2

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?

11
  • What does your entire result look like? The result in your question must be wrapped in something, quotes if nothing else. Commented Nov 24, 2010 at 13:02
  • Show us the webservice method signature, including any attributes. Commented Nov 24, 2010 at 13:07
  • I suspect you are returning your json serialized data within a webservice method that is itself json serialized, but impossible to tell without seeing the method signature. Commented Nov 24, 2010 at 13:11
  • Nick: When I look at the result in a browser debugger, it is wrapped in quotes (""). When I test run the method by opening the .asmx page directly, the json result is wrapped in XML tags: <string xmlns="tempuri.org/">[ { "ConstructLabel": "Construct label 1", "ConstructType": 2, }, { "ConstructLabel": "Construct label 2", "ConstructType": 3, } ]</string> Commented Nov 24, 2010 at 16:56
  • 1
    Running the asmx page directly will not give you a json output, the web service will only emit json when the datatype is set to indicate json (as jquery will when you use it to call the service), if you just request it in the browser you will get XML. Commented Nov 24, 2010 at 19:09

1 Answer 1

1

You shouldn't manually serialize the JSON. The ScriptService will do that for you automatically if you define it like this:

[WebMethod]
public List<Construct> GetConstructList()
{
  return new ConstructList();
}
Sign up to request clarification or add additional context in comments.

4 Comments

This is what I originally thought. However, I cannot get my webmethods to return anything except XML unless I manually serialize to JSON. I have added this entry to web.config, which I thought would enable default JSON, but it doesn't work:
<add verb="" path=".asmx" validate="false" type= "System.Web.Script. Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
Which version of ASP.NET are you running? That ScriptHandlerFactory is what you would use with 2.0 (assuming the ASP.NET AJAX Extensions are install), but you wouldn't have DataContractJsonSerializer in 2.0. If your site is running a later version, you'd need to update that ScriptHandlerFactory reference. More info: encosia.com/2010/03/08/…
I'm running ASP.NET 4, and hadn't realised (until I read your post) that the ScriptHandlerFactory and all other asmx JSON requirements are already built in. I fiddled around a bit with web.config, and removed the various references I had added as part of my unsuccessful attempts, and now it works exactly as expected! Many thanks indeed! Also: many thanks for writing your blog - I've found it an excellent and very well written source of really useful information.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.