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

今天在介绍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格式)

如下面的效果

image

那么,如何让这些结果用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<ContactsData>
{
// your service code here...
}
Once that's in place you can use JSONP by adding $format and $callback to URLs, for example:
http://<host>/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,我们只需要在有关的类型上面加上即可

image

 

然后,在请求地址中添加$format=json这样的字样即可

http://localhost:1142/OrderService.svc/Customers('ALFKI')/Orders?$format=json

 

返回的json数据,大致如下

image

posted @ 2010-10-27 19:50  陈希章  阅读(3224)  评论(11编辑  收藏  举报