4

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.

rick schott
  • 21,012
  • 5
  • 52
  • 81
ChrisP
  • 9,796
  • 21
  • 77
  • 121

7 Answers7

7

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/

Dave Ward
  • 59,815
  • 13
  • 117
  • 134
6

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.

rick schott
  • 21,012
  • 5
  • 52
  • 81
3

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

Community
  • 1
  • 1
Kelsey
  • 47,246
  • 16
  • 124
  • 162
  • @chrisp Did you ever get your issue sorted out? If this answer or another helped you, you should set an accepted answer so that others reading this question can locate the solution that helped you. – Kelsey Aug 18 '10 at 16:16
1

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();
}
James Black
  • 41,583
  • 10
  • 86
  • 166
  • Don't you mean `String s = "{'result': 'success'}";` ? And obviously you've posted C# and the question was VB.Net (I know everyone does that) – MarkJ Nov 05 '09 at 11:00
  • @markJ - I didn't have an example in VB.NET, but I was mainly showing the annotations, but I didn't think about the language either. And I removed the double quote. Thanx. – James Black Nov 05 '09 at 13:51
0

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);
}
Jeff Sternal
  • 47,787
  • 8
  • 93
  • 120
0

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
Jeff Sternal
  • 47,787
  • 8
  • 93
  • 120
Mark Holland
  • 846
  • 4
  • 8
0

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/

Thomas
  • 33,544
  • 126
  • 357
  • 626