views:

1328

answers:

2

I have a web service returning JSON, but now I'd like to modify it to allow callers to specify a callback function so the return goes from: JSON DATA to specifiedFunction(JSON DATA); The way I'm returning JSON right now is just by returning an instance of an object and having .NET do its serialization magic, if I change to just returning a string I can add the name of the function and the brackets around the data but then I end up with quotation marks in the return, because its a string and I don't want those. So how can I go about it?

Reason for this is we want developers calling our API to be able to use the dynamic script tag as explained here http://www.xml.com/pub/a/2005/12/21/json-dynamic-script-tag.html

A: 

I don't know what version of HTML they're using, but in all the versions that I've used, the src attribute in a script tag has to be a URL. They're somehow using a function instead, and I don't see that working.

Have you actually seen a dynamic script tag work?

John Saunders
I've not used it personally but as far as I know it can be done. There are examples of web services out there that return in the style I'm after, for example http://www.geonames.org/export/JSON-webservices.html
mbehan
I'm not so concerned about these services as I am the browsers. Someone more up to date can correct me, but I don't expect anything other than a URL to work in the src attribute.
John Saunders
regardless, any help on how to format the return as required will be greatly appreciated :)
mbehan
+1  A: 

The technique you are after is called JSONP (JSON with Padding).

See How to support JSONP in WCF services:

The JsonPEncoder is a wrapping encoder on the WCF JSON encoder. It delegates most calls to the wrapped encoder. The WriteMesage methods have been overriden to pad the outgoing message with the callback method. The JsonBehavior is used on the service operation to enable JSONP encoding for that operation. The query parameter of the URI that holds the callback function name is specified as the CallBack property of the behavior.

Crescent Fresh
Wow. I'd heard of JSONP, but didn't know it sent the callback function name. Any links to which browsers support that src=expression syntax?
John Saunders