您的位置:首页 > Web前端 > JavaScript

ADO.NET Data Service如何直接支持用Json格式返回数据

2010-10-27 11:50 891 查看
今天在介绍WCF及其在项目开发中应用时,再次提到了ADO.NET Data Service。关于这个主题,其实之前我写过不少内容,有兴趣可以参考
http://zzk.cnblogs.com/s?w=blog%3Achenxizhang%20ado.net%20data%20service
 
同时,微软有一篇非常详细的文档
http://msdn.microsoft.com/en-us/library/cc907912.aspx
 
我们知道,ADO.NET Data Service是支持两种数据格式的:xml和json.默认是xml(具体来说是atom格式)
如下面的效果



那么,如何让这些结果用json格式返回呢?
 
比较遗憾的是,我们暂时不能直接通过设置就完成这个需求。但是有一个开源的项目,提供了一个解决方案,如下
http://code.msdn.microsoft.com/DataServicesJSONP
The net effect is that if you include this code in your project, you just need to add a single attribute to your Data Service to make it support JSONP:
[JSONPSupportBehavior]
public class SampleService : DataService
{
// your service code here...
}
Once that's in place you can use JSONP by adding $format and $callback to URLs, for example: http:///SampleService.svc/People?$format=json&$callback=cb Of course, you can still use all the other Data Services URL options in addition to these.  
使用起来很简单,他是写好了一个Behavior的Attribute,我们只需要在有关的类型上面加上即可



 
然后,在请求地址中添加$format=json这样的字样即可
http://localhost:1142/OrderService.svc/Customers('ALFKI')/Orders?$format=json
 
返回的json数据,大致如下


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: