2012年3月24日土曜日

Returning dynamic JSON from ASP.Net

I have an ASP.Net web service that I want to return a JSON response. The method that I am working on in particular calls another web service that already gives me a JSON response. All I want to do is return that to the caller of my webservice (it will be a .htm/.js caller).

I have already found a way to make it work, but it doesn't seem optimal. If I define some local objects in my web service that look like the JSON response I get from the third party web service, I can deserialize the response into my local objects, and return the object from my web service. If I call the service from the browser with the JSON request type, I get back the correct JSON response. But in this case I have taken a JSON string, converted it to an object and back again, which seems like too much work. Plus, I'll have an extra layer of objects that have to be kept in sync with the third party response.

If I just return the JSON that I get from the third party webservice (as a string), in the browser I get a string that can't be EVAL'd into a js object. It has quotes around the whole thing and all the internal quotes are escaped, etc. It is basically just a string, not JSON.

So, the question is, how can I define a web service method that returns any JSON that can be called from a simple htm/js client and get it to return valid (ready to eval) JSON? What return type should I be using?

Backslider

ASP.NET AJAX web services only support returning objects. These objects will be serialized by the AJAX services layer. There is no returntype to hold raw JSON , and skip this serialization.

However if you return the JSON as a string, you should be able to eval the response once to get the string response from thirdparty webservice(If you use a proxy generated by ASP.NET AJAX it would returned an already eval'ed response). Once you get the string, you should be able to eval it again to get the actual js object.


Have you tried letting your server convert it into a .Net object?

0 件のコメント:

コメントを投稿