ChrisP
ChrisP

Reputation: 10116

How to return JSON from ASP.NET .asmx?

I have the following test method:

Imports System.Web

Imports System.Web.Services

Imports System.Web.Services.Protocols


<WebService(Namespace:="http://tempuri.org/")> _

<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _

<System.Web.Script.Services.ScriptService()> _

Public Class DemoService
 Inherits System.Web.Services.WebService

<WebMethod()> _
Public Function GetCustomer() As String
    Return "Microsoft"
End Function


End Class

Even with the ResponseFormat attribute added the response is still being returned as XML rather than JSON.

Thoughts appreciated.

Upvotes: 4

Views: 35522

Answers (7)

Thomas
Thomas

Reputation: 34188

Sorry to answer for old post. if we need to return json of a specific object then we can follow this approach too.

[WebService(Namespace = "http://contoso.com/")] 
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]System.Web.Services.WebService
[ScriptService]
public class services :WebService  
{    
    [WebMethod(CacheDuration = 60)]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public List<TestObject> GetObjectCollection()
    {
           return YourService.GetObjectCollection().ToList();
    }
}

good article exist from this link https://cmatskas.com/getting-json-data-using-an-asmx-web-service/

Upvotes: 0

Dave Ward
Dave Ward

Reputation: 60580

I'm a bit late to this question, but hopefully this helps you or anyone else stumbling onto this thread later.

You definitely can use ASMX services to communicate in JSON.

Your service code looks okay. Since you aren't showing how you're calling it, I'll bet that's where your problem lies. One requirement for getting JSON out of ASMX "ScriptServices" is that you must call them with the correct content-type header and you must use a POST request. Scott Guthrie has a good post about the reasoning behind those requirements.

So, if you just request DemoService.asmx/GetCustomer in a browser, you're going to get XML. However, if you make a POST request with an application/json content-type, you'll get the same result serialized as JSON.

If you're using jQuery, here's an example of how you would request your DemoService on the client-side:

$.ajax({
  type: "POST",
  contentType: "application/json",
  url: "DemoService.asmx/GetCustomer",
  data: "{}",
  dataType: "json",
  success: function(response) {
    // Prints your "Microsoft" response to the browser console.
    console.log(response.d);
  }
});

More here: http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/

Upvotes: 7

Mark Holland
Mark Holland

Reputation: 846

I've used ashxes for this problem too. To be honest I didn't know webservices had that ResponseFormat attribute. That said I think I still prefer the ashx route for lightness and control.

There's some peripheral details left out here, to concentrate on the bit you'd need.

    Imports Newtonsoft.Json
    Imports Newtonsoft.Json.Linq

    Namespace Handlers.Reports

        Public MustInherit Class Base
            Implements IHttpHandler, SessionState.IRequiresSessionState


            Protected data As String()() = Nothing
            Private Shared ReadOnly JsonContentType As String = "application/json" 

          Public Sub ProcessRequest(ByVal context As System.Web.HttpContext) Implements System.Web.IHttpHandler.ProcessRequest

                Try

                    Me.GetData()
                    Me.BuildJsonResponse(context)

                Catch ex As Exception

                End Try

                context.Response.End()

            End Sub

     Private Sub BuildJsonResponse(ByVal context As System.Web.HttpContext)

                context.Response.AddHeader("Content-type", Base.JsonContentType)

                Dim json = Me.BuildJson()
                context.Response.Write(json)

            End Sub

            Private Function BuildJson() As String

                If Not Me.data Is Nothing Then

                    Return String.Format("{{data: {0}, pageInfo: {{totalRowNum:{1}}}, recordType: 'array'}}", JsonConvert.SerializeObject(Me.data), Me.totalRows)

                End If

                Return String.Empty

            End Function
 End Class

End Namespace

Upvotes: 0

Jeff Sternal
Jeff Sternal

Reputation: 48583

If you're restricted to the 2.0 Framework, you can use the JavaScriptSerializer, from the System.Web.Extensions assembly, like this (in C#):

[WebMethod()]
[ScriptMethod()]
public static string GetJsonData() {
    // data is some object instance
    return new JavaScriptSerializer().Serialize(data);
}

Upvotes: 0

James Black
James Black

Reputation: 41858

This is what I do, though there is probably a better approach, it works for me:

[WebMethod]
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
public string retrieveWorkActivities(int TrackNumber)
{
            String s = {'result': 'success'};
            return s.ToJSON();
}

Upvotes: 1

Kelsey
Kelsey

Reputation: 47726

Why not just use an ashx file? It's a generic handler. Very easy to use and return data. I use these often in place of creating a web service as they are much lighter.

An example of the implementation in the ashx would be:

// ASHX details
DataLayer dl = GetDataLayer();
List<SomeObject> lst = dl.ListSomeObjects();
string result = "";
if (lst != null)
{
    JavaScriptSerializer serializer = new JavaScriptSerializer();
    result = serializer.Serialize(lst);
}
context.Response.ContentType = "application/json";
context.Response.Write(result);
context.Response.End();

If you do need to use a web service though you could set the ResponseFormat. Check out this SO question that has what you are looking for:

How to let an ASMX file output JSON

Upvotes: 3

rick schott
rick schott

Reputation: 20617

Do you have .NET 3.5 or greater installed?

ScriptServiceAttribute is in .NET 3.5 and 4.0.

Also, clear your ASP.NET temp files, the dynamic proxy could be cached.

Upvotes: 6

Related Questions