0

I'm creating a web service using ASP.NET, C#, currently it is giving XML, but I'm going to get JSON, this is how I create my webmtheod:

[Webservice(Namespace="http://myurl)]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfiles_1)]
[System.ComponentModel.ToolboxItem(false)]

[WebMehod]
public string myfunction()
{

string r = "......";


return r;
}

these are in an ASMX file, which I call it in my browser

1
  • this function returns me XML output but I'm going to get JSON, how can I get JSON? I think I should use .NET serialization functions, but how? Commented Nov 20, 2012 at 14:09

2 Answers 2

3

If you want to return JSON from your method you will need to use the ScriptMethod attribute.

Structure your method like this, notice the [ScriptMethod(ResponseFormat = ResponseFormat.Json)] attribute.

    [WebMethod()]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string MyMethod()
    {

    }

At the moment, this method is returning a string, which can be a JSON structured string. However, you may be better to return an object, which can be parsed as JSON. List<string> as well as Class's with standard data-types, like integers, strings etc are great for this. You can then return just that object. the ScriptMethod takes care of transforming it into JSON.

For example:

The Class you want to return:

      public class MyJson
      {
         public int ID;
         public List<string> SomeList;
         public string SomeText;
     }

And your method to return a populated MyJson

        [WebMethod()]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public MyJson MyMethod()
        { 
          MyJson m = new MyJson();
          m.ID = 1;
          m.SomeText = "Hello World!";
          m.SomeList = new List<string>();
          m.SomeList.Add("Foo");
          m.SomeList.Add("Bar");

          return m;
        }

The return JSON will be structured just like the class. The property names will be used too, and your List<string> will become an array

Call this using AJAX. JQuery in this case:

$(document).ready(function(){

      $.ajax({
            type: "POST",
            url: "/YourPage.aspx/MyMethod",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {

             // content will be in here... I.E
             var id = msg.d.ID;
             var st = msg.d.SomeText;
             var sl = msg.d.SomeList;
             var i = sl.length;
            var firstSlItem = sl[0];
            }
        });
});
Sign up to request clarification or add additional context in comments.

3 Comments

thanks, but it seems that I'm still getting an XML (it is now structured like my class), how should I call my webservice in my browser to get json output?
Call it with AJAX, making sure to specify the Datatype as JSON. I will add some example code.
If it's still returning AJAX then see this page stackoverflow.com/questions/2749954/… - don't forget to mark all as answered if they help, and upvote other answers if they help you too.
2


An alternate approach would be to use JavaScriptSerializer to return JSON as a string:

[System.Web.Services.WebMethod()]
public string GetItems() {
    List<string> listOfItems = new List<string> {"asdf", "qwerty", "abc", "123"};

    JavaScriptSerializer js = new JavaScriptSerializer();
    string json = js.Serialize(listOfItems);

    return json;
}


...be sure to use this import:

using System.Web.Script.Serialization;


...and you will then have to parse the result in javascript / jQuery like this:

var result = "";

$.ajax({

      // ...other properties defined here...

      success: function (response) {
            result = JSON.parse(response.d);
      }
});

// the List<string> has been parsed into an array:
for (var i = 0, len = result.length; i < len; i++) {
      alert(result[i]);
}


If you convert an instance of a class in this same way, such as @Darren's example here, it will then be parsed as a javascript object-literal.

Also note that in an .asmx file webmethods are declared as public instance methods, as opposed to public static in .aspx files.

Comments

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.