27

I am using .Net framework 2.0 / jQuery to make an Ajax call to a 2.0 web service. No matter what I set the contentType to in the ajax call, the service always returns XML. I want it to return Json!

Here is the call:

      $(document).ready(function() {
         $.ajax({
            type: "POST",
            url: "DonationsService.asmx/GetDate",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
              // Hide the fake progress indicator graphic.
              $('#RSSContent').removeClass('loading');

              // Insert the returned HTML into the <div>.
              $('#RSSContent').html(msg.d);
            }
          });
        });    

Here is what the request header looks like in Fiddler:

POST /DonationsService.asmx/GetDate HTTP/1.1
x-requested-with: XMLHttpRequest
Accept-Language: en-us
Referer: http://localhost:1238/text.htm
Accept: application/json, text/javascript, */*
Content-Type: application/json; charset=utf-8
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; eMusic DLM/4; .NET CLR 2.0.50727)
Host: localhost:1238
Content-Length: 2
Connection: Keep-Alive
Pragma: no-cache

I have tried setting the contentType to 'text/json' and get the same results.

Here is the web service method:

<WebMethod()> _
Public Function GetDate() As String

    'just playing around with Newtonsoft.Json
    Dim sb As New StringBuilder
    Dim sw As New IO.StringWriter(sb)
    Dim strOut As String = String.Empty

    Using jw As New JsonTextWriter(sw)
        With jw
            .WriteStartObject()
            .WritePropertyName("DateTime")
            .WriteValue(DateTime.Now.ToString)
            .WriteEndObject()
        End With
        strOut = sw.ToString
    End Using

    Return strOut

End Function

and here is what it returns:

<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://DMS.Webservices.org/">{"DateTime":"11/13/2008 6:04:22 PM"}</string>

Does anyone know how to force the web service to return Json when I ask for Json?

Please don't tell me to upgrade to .Net Framework 3.5 or anything like that (I'm not that stupid). I need a 2.0 solution.

2

7 Answers 7

35

It's no problem to return JSON from ASMX services in ASP.NET 2.0. You just need the ASP.NET AJAX Extensions installed.

Do be sure to add the [ScriptService] decoration to your web service. That's what instructs the server side portion of the ASP.NET AJAX framework to return JSON for a properly formed request.

Also, you'll need to drop the ".d" from "msg.d" in my example, if you're using it with 2.0. The ".d" is a security feature that came with 3.5.

1
  • 1
    Sadly, that encosia link is now triggering an attack page warning in my browser.
    – TrojanName
    Commented Jan 26, 2017 at 15:25
12

The response is wrapped in a element because you're method says it will return a string. You could use this to be able to send plain json, but your wsdl will be fooled (the function is void but does respond data).

[WebMethod(Description="return pure JSON")]
public void retrieveByIdToPureJSON( int id )
{
  Context.Response.Write( JsonConvert.SerializeObject( mydbtable.getById(id) );
}

Good luck, tom

Btw: see Newtonsoft.Json for JsonConvert

2
  • 4
    That simple. Change from Function to Sub (in Vb.net) and drop the return but use a response.write to output. 2 weeks of trying various things to get rid of that nasty <?xml version="1.0" encoding="utf-8"?> when i did a Return. Saved my day . Tnxs
    – KriZ
    Commented Sep 18, 2013 at 7:14
  • I want to hug you right now, took me hours to find your solution :) Commented Mar 31, 2017 at 12:56
10

You need to decorate your web method with the following:

[ScriptMethod(ResponseFormat = ResponseFormat.Json)]

You've got the rest right :)

More info at Encosia and Andrew Roland's Blog

EDIT: As noted below this is .NET 3.5 only (I was unaware of this, my bad).

2
  • 2
    The 'ResponseFormat' enumeration is only supported from 3.5 onwards, OP asked how to do in FW 2.0.
    – Kev
    Commented Nov 14, 2008 at 1:19
  • 2
    @Omu Original Poster as in the person who asked the question (or in forums the person who started the thread)
    – Darko
    Commented Jun 17, 2011 at 0:54
2

You probably can't do anything other than XML or binary serialization in .NET 2.0. If you're not using an autogenerated web reference then don't bother with ASMX. Just use an ASPX or ASHX instead.

0
2

You can use the Jayrock library Quick start for asp.net

This allows you to write a http handler to return you json.

<%@ WebHandler Class="JayrockWeb.HelloWorld" %>

namespace JayrockWeb
{
    using System;
    using System.Web;
    using Jayrock.Json;
    using Jayrock.JsonRpc;
    using Jayrock.JsonRpc.Web;

    public class HelloWorld : JsonRpcHandler
    {
        [ JsonRpcMethod("greetings") ]
        public string Greetings()
        {
            return "Welcome to Jayrock!";
        }
    }
}
1
  • I actually looked at that as a possible solution, if I couldn't do it with plain 'ol asp.net. Thanks.
    – camainc
    Commented Nov 14, 2008 at 14:28
1

It's also possible to just write up your own quick JSON converter using Refelction.

Dim sb As New StringBuilder("{")
For Each p As PropertyInfo In myObject.GetType().GetProperties()
    sb.Append(String.Format("""{0}"":""{1}"",", p.Name, p.GetValue(myObject,  
              Nothing).ToString()))
Next p

//remove the last "," because it's uneeded.
sb.Remove(sb.Length - 1, 1)

sb.Append("}")    
0

I may not be 100% correct on this but I'm sure .net webservices are XML/SOAP based.

You would need to override the default behavior of the webservice. I'm not entirely sure that this would even be possible.

I know this won't be the most useful answer, but may get you headed in the right direction.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.