4

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.

casperOne
  • 73,706
  • 19
  • 184
  • 253
Eugene
  • 10,957
  • 20
  • 69
  • 97

2 Answers2

3

JSON.net is quite popular and seems to be what you're after.

aligray
  • 2,812
  • 4
  • 26
  • 35
  • 1
    JSON.net's [SelectToken](http://james.newtonking.com/projects/json/help/SelectToken.html) did the trick! – Eugene Jun 03 '11 at 21:53
1

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.

S P
  • 4,615
  • 2
  • 18
  • 31