Return JSON from ASMX web service, without XML wrapper?
Asked Answered
W

1

6

I need to get Json data from a C# web service.

I know there are several questions based on this, trust me I have read through quite a few but only to confuse me further.

This is what I have done :

In my web service I have included : [System.Web.Script.Services.ScriptService] for the class & [ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)] for the method

I have also used a JavaScriptSerializer() to convert my data to a string

I am calling this service using $.getJSON()

If I don't use that I get an Cross domain reference error.

To do this I had to setup m service to get the callback function name so I am passing this.Context.Request["callback"] + serialized Json Data;

But in the output I get it wrapped in

< string xmlns="http://XYZ...">  

The data within the tags is in the format I need

I also tried setting content type using : $.ajaxSetup({ scriptCharset: "utf-8" , contentType: "application/json; charset=utf-8"});

But still no success.

Addded later: I accepted frenchie's anwser beacuse I know it is the correct approach but I stil cud not get it to work... I just put the webservice & website in the same domain & used xml, I know it wasnt the best way, but I had spent 2 days on it & could not afford to waste more.

Whithersoever answered 6/12, 2011 at 19:15 Comment(9)
Are you using WCF, ASMX? You could very easily return JSON data using ASP .NET MVC as well.Fivespot
Have you considering using a RESTful service? That might work better for you in this case.Ernaldus
I am using ASMX... Very new to C# web services....I generally use PHP & its done so easily.Whithersoever
ASMX is the old, legacy technology, and should not be used for new development. You should use WCF instead.Hasten
@Zoidberg: can u please give me some pointers to restful... I believe i am using that.. <webServices> <protocols> <add name="HttpSoap"/> <add name="HttpPost"/> <add name="HttpGet"/> <add name="HttpPostLocalhost"/> <add name="Documentation"/> </protocols> </webServices>Whithersoever
@Whithersoever Take a look at this link ajaxpatterns.org/RESTful_Service It should give you enough information to get started.Ernaldus
@Whithersoever This one describes a restful service using JSON bitworking.org/news/restful_jsonErnaldus
It is essentially using HTTP protocol to make calls.It is easy to send a JSON post as well, so it is all pretty wide open.Ernaldus
Possible duplicate of Asmx web service how to return JSON without an XML wrapper?Vocalism
M
4

Use this:

var JsonString = ....;
$.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    url: "YourWebServiceName.asmx/yourmethodname",
    data: "{'TheData':'" + JsonString + "'}",
    dataType: "json",
    success: function (msg) {
        var data = msg.hasOwnProperty("d") ? msg.d : msg;
        OnSucessCallBack(data);
    },
    error: function (xhr, status, error) {
        alert(xhr.statusText);
    }
});

function OnSuccessCallData(DataFromServer) {
 // your handler for success    
}

and then on the server side, in the code behind file that's auto-generated in your AppCode folder, you write something like this:

using System.Web.Services;
using System.Web.Script.Serialization;

    [System.Web.Script.Services.ScriptService]
    public class YourWebServiceName : System.Web.Services.WebService
    {
        [WebMethod]
        public string yourmethodname(string TheData)
        {
          JavascriptSerializer YourSerializer = new JavascriptSerializer();
          // custom serializer if you need one 
          YourSerializer.RegisterConverters(new JavascriptConverter  [] { new YourCustomConverter() });

          //deserialization
          TheData.Deserialize(TheData);

          //serialization  
          TheData.Serialize(TheData);
        }
    }

If you don't use a custom converter, the properties between the json string and the c# class definition of your server-side object must match for the deserialization to work. For the serialization, if you don't have a custom converter, the json string will include every property of your c# class. You can add [ScriptIgnore] just before a property definition in your c# class and that property will be ignored by the serializer if you don't specify a custom converter.

Medalist answered 6/12, 2011 at 19:27 Comment(20)
Do I need to serialize the data using JavaScriptSerializer() before sending or do I just send the data as it is?Whithersoever
yes, you need to serialize it. You can either use straight serialization or use a custom serializer. Updating code.Medalist
Just updated the code. This is verbatim what I use and it works. Let me know if this helps.Medalist
I was doing it this way: JavaScriptSerializer js = new JavaScriptSerializer(); string strJSON = js.Serialize(locs); locs is an array of objects.. Is this an acceptable way?Whithersoever
Yes, if you have an array of objects the serializer will do the job just fine. I really recommend using a custom converter because the property names you have can be shortened when you're serializing the objects for the web. You got your thing working?Medalist
Nope i use the serializer, I use the contentType: "application/json; charset=utf-8", still it is enclosed in the xml tags... Now I was trying to use the DataContractJsonSerializer but it gives me error : The type 'System.Runtime.Serialization.XmlObjectSerializer' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Runtime.Serialization, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.Whithersoever
Why do you need xml serialization if you're using json???? If you really need it, add "using System.Runtime.Serialization;" in the same part of the code where I added my using statements. In c#, the using statements enable you to use classes defined elsewhere. For instance, "using System.Web.Script.Serialization" tells the compiler to bring this file into your code library to work with the json serializer object. I recommend you use the code I wrote because GET requests are more error-prone and less secure than POST requests.Medalist
I really dont need it, I guess my serialization worked just fine but I was just trying something that I saw here https://mcmap.net/q/122329/-asp-net-json-web-service-response-format/1028488Whithersoever
Also I had already added these, using System.Runtime.Serialization; using System.Runtime.Serialization.Json; still I was getting the errorWhithersoever
Sure... Thanks for all your help. I am still stuck though... Will do so as soon as I get a break through.Whithersoever
as I said the webservice still returns data in the xml tags <string xmlns="xxx.yyy.com"> [{"ID":"1...... this is what i get.. & I want only [{"ID":"1.....Whithersoever
If you use the code I have, you should get [{"ID":"1.... I think you need to remove the XML part altogether; I never user it and just stick to pure framework json serialization. That's how it's done in .net and it's pretty straight forward.Medalist
I dont have any XML stuff in there, I was just experimenting. Is that format returned by your webservice even when it is in opened by itself in a browser?Coz In my case when I open it individually in a browser it shows <string xmlns="http:/fdas/"> [{"ID":"1", & when I call it using $.ajax in my javascript, it gives me an error Uncaught SyntaxError: Unexpected token <.... when I check what it has returned in resources, it shows : <?xml version="1.0" encoding="utf-8"?> myfunc:1 Uncaught SyntaxError: Unexpected token < <string xmlns....Whithersoever
I accepted your anwser beacuse I know it is the correct approach but I stil cud not get it to work... I just put the webservice & website in the same domain & used xml.....Whithersoever
ok, go with what works, that's the way to do it. Happy coding!Medalist
Sorry to bring up old questions, but I seem to be having the same problem, and I don't quite understand what exactly you're doing. All I do is call .Serialize(tasks); where tasks is a list of custom objects. It's my understanding that this should return an array of JSON objects. What my web page gets back is an array of JSON objects embedded in XML. I'm using ASMX because I'm updating a legacy company Intranet site to include a specific feature, in order to match an upcoming Intranet site that uses MVC. Any ideas?Unamerican
If it's returning XML it's because the request sent from the page didn't specify the return format correctly. Make sure to specify contentType and dataType like in the answer.Medalist
I was originally using $.post, but I changed to $.ajax to see what would happen. In my MVC method, I get back an array of JSON objects, like this: "[{"id":1006,"system":1,...},{"id":1007,"system":1, ...}]" but using $.ajax, I get back an object containing an array, I think. It looks like this: {"d":[{"__type":"TaskManagement.Task","id":1006,...},{"__type" :"TaskManagement.Task","id":1007,...}]}. Can you help me either use this or get a response like the other?Unamerican
Never mind, I figured out how to do it. I just needed to think a little bit about how JSON objects work. In my function (r), I just needed to reference r.d to get the array, i.e. r.d[i].id. Thanks for the help though!Unamerican
No you do NOT need to serialize manually. When properly set up, the Framework will detect whether you are requesting XML or JSON and will spin up the necessary serializer. You should not return a json string, you should not return void and hack the Response - just return the natural type that your function would return if you weren't targetting JSON. https://mcmap.net/q/122328/-asmx-web-service-how-to-return-json-and-not-xmlVocalism

© 2022 - 2024 — McMap. All rights reserved.