ASP.NET WebService is Wrapping my JSON response with XML tags

Mike picture Mike · Jan 13, 2010 · Viewed 37.7k times · Source

I'm not sure where I'm going wrong of what I'm missing.

I'm building an ASP.NET 2.0 (on the .Net 3.5 framework) Web application and I am including a webservice. Note that this is not an MVC project. I wish to expose a method which will return a JSON string; formatted to feed the jqGrid jQuery plugin.

This is the preliminary test method I've implemented in my service: thanks to (Phil Haack's Guide for MVC)

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string getData()
{
    JavaScriptSerializer ser = new JavaScriptSerializer();

    var jsonData = new
    {
        total = 1, // we'll implement later 
        page = 1,
        records = 3, // implement later 
        rows = new[]{
          new {id = 1, cell = new[] {"1", "-7", "Is this a good question?", "yay"}},
          new {id = 2, cell = new[] {"2", "15", "Is this a blatant ripoff?", "yay"}},
          new {id = 3, cell = new[] {"3", "23", "Why is the sky blue?", "yay"}}
        }
    };

    return ser.Serialize(jsonData); //products.ToString();
}

When invoked this is returning (formatted for clarity):

<?xml version="1.0" encoding="utf-8" ?> 
<string  mlns="http://tempuri.org/">
{
  "total":1,
  "page":1,
  "records":3,
  "rows":
    [
      {"id":1,"cell":["1","-7","Is this a good question?","yay"]},
      {"id":2,"cell":["2","15","Is this a blatant ripoff?","yay"]},
      {"id":3,"cell":["3","23","Why is the sky blue?","yay"]}
    ]
}
</string> 

How would I achieve the above response without the xml wrappings?

Answer

Patrick Karcher picture Patrick Karcher · Jan 13, 2010

In your code, don't "return" the json. Use instead:

Context.Response.Write(ser.Serialize(jsonData));

Then you'll be good.

The regular return command helps you by putting in a more proper service format. Some would say it'd be better form to use this, and unwrap your json on the client from this format. I say, just spit down the stuff exactly how you want to use it!