How would I go about about using LINQ to JSON in the .net 4 Client Profile in C#. I'd like to query 开发者_高级运维certain json responses as shown in msdn blog post without having to write out a contract (datacontract, servicecontract, etc). I really only need to query(read) the response, I don't need to modify the json response. (Also would a datacontract be faster than LINQ to JSON?)
Alternatively I could use XML or the full .net 4 framework, but I'm hoping that this can be avoided. I can use external libraries if it's better than installing the whole framework.
JSON.net is quite popular and seems to be what you're after.
If your service is used by Ajax (jQuery) clients, you will get the best performance by using JSON.
Another recommendation; in order to get rid of the same domain policy, I recommend you to enable crossDomainScriptAccessEnabled functionality:
<webHttpBinding>
<binding name="myHttpBinding" crossDomainScriptAccessEnabled="true" />
</webHttpBinding>
Regarding the DataContract; in your scenario, a DataContract is not really needed.
Example code:
Your Service:
[ServiceContract] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class BlogService { [OperationContract] [WebGet(ResponseFormat = WebMessageFormat.Json)] public List<Article> GetBlogArticles() { return Article.GetDummyArticles.ToList(); } }
Article Class (excerpt):
public class Article { public string Title { get; set; } public string Body { get; set; } public static IEnumerable<Article> GetDummyArticles() { yield return new Article { Title = "Article 1", Body = "sdlkfjsdlkfjskl" }; yield return new Article { Title = "Article 2", Body = "sfsfsdfd23434wfdfsfdfkfjskl" }; } }
For your scenario I actually can't find a reason to use any (3rd-party) library since WCF4 already contains native support for JSON with or without Padding.
精彩评论