views:

343

answers:

3

I wrote a [WebMethod] that return a string that store a serialized object

[WebMethod]
public string doStuffs() {
...
return JavaScriptConvert.SerializeObject(myObj); 
// JSON Serializer library is JSON.NET 1.3.1, for MONO
}

When I call the method with a $.post from JQuery:

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

The problem is the response. Here what I get:

<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://localhost:8080/papi"&gt;{
 "field1" : "value1", "field2 : "value2", etc etc}</string>

Why JSON response has been encapsulated inside an XML? I can see from HTTP Response header is (wrongly?) set to:

Content-Type text/xml; charset=utf-8

How do I switch the response content type? Thanks.

A: 

If I do:

$.post(
    "/web/doStuffs",
    { username: $("#username").val() },
    function(data){
      var obj = $(data).children();
    },     
    "xml"
);

I will have JSON in var obj ready to get parsed with JS. This should work well.

Kind of defeats the purpose of JSON though?
Mikko Rantanen
A: 

Does Mono support DataContractJsonSerializer?

UPDATE: it would appear so, but maybe there are bugs?

kenny
A: 

AFAIK WebMethods return objects which get serialized automatically by ASP.NET. The default serializer is SOAP, as that used to be the expected format for web services.

However, ASP.NET AJAX in System.Web.Extensions has a replacement handler that uses a JSON serializer. See http://vampirebasic.blogspot.com/2009/04/aspnet-ajax-in-mono.html for how to register it.

mhutch