A Brief Overview of Newton JSON

download A Brief Overview of Newton JSON

If you can't read please download the document

description

LINQ to JSON is good for situations where you are only interested in getting values from JSON, you don't have a class to serialize or deserialize to, or the JSON is radically different from your class and you need to manually read and write from your objects.

Transcript of A Brief Overview of Newton JSON

  • 1. Json.NETPopular high-performanceJSON framework for .NET

2. Json.NETJson.NET is a popular high-performance JSON framework for .NETFeatures Flexible JSON serializer for converting between .NET objects and JSON LINQ to JSON for manually reading and writing JSON High performance, faster than .NET's built-in JSON serializers Write indented, easy to read JSON Convert JSON to and from XML Supports .NET 2, .NET 3.5, .NET 4, Silverlight, Windows Phone and Windows 8.The JSON serializer is a good choice when the JSON you are reading or writing maps closely to a .NETclass.LINQ to JSON is good for situations where you are only interested in getting values from JSON, you don'thave a class to serialize or deserialize to, or the JSON is radically different from your class and you needto manually read and write from your objects.Thats cool, JSON is lightweight and there is no un-necessary data using overhead bandwidth like as forXML. The Web API has a built-in capability to serialize the return value as JSON format but some situationexists (in another service or Page Method in the code behind of the WebForm) that the developer needs toserialize data in JSON format. 3. SerializationLets say that for example I want to send data to the browser. All I have to do isto create an ExpandoObject (my new favourite .Net class!) and serialize it usingJson.Net JsonConvert.SerializeObject().dynamic foo = new ExpandoObject();foo.Bar = "something";string json = Newtonsoft.Json.JsonConvert.SerializeObject(foo); 4. DeserializationJson.Net offers a great way to deserialize a JSON string into a dynamic usingthe JObject (you can find it under the Newtonsoft.Json.Linq namespace andhere the details).dynamic foo = JObject.Parse(jsonText);string bar = foo.Bar; // bar = "something" 5. JSON MergeThe most visible new feature in this release is the ability to quickly merge JSON using theMerge method added to JObject and Jarray.JObject o1 = JObject.Parse(@"{'FirstName': 'John','LastName': 'Smith','Enabled': false,'Roles': [ 'User' ]}");JObject o2 = JObject.Parse(@"{'Enabled': true,'Roles': [ 'User', 'Admin' ]}");o1.Merge(o2, new JsonMergeSettings{// union array values together to avoid duplicatesMergeArrayHandling = MergeArrayHandling.Union});string json = o1.ToString(); 6. Dependency InjectionThe low-level ConstructorInfo properties on JsonObjectContract, used when creating objects during deserialization, are nowobsolete and have been replaced with functions. Also Json.NET no longer immediately throws an exception if it tries todeserialize an interface or abstract type. If you have specified a way for that type to be created, such as resolving it from adependency inject framework, then Json.NET will happily continue deserializing using that instance.public class AutofacContractResolver : DefaultContractResolver{private readonly IContainer _container;public AutofacContractResolver(IContainer container){_container = container;}protected override JsonObjectContract CreateObjectContract(Type objectType){JsonObjectContract contract = base.CreateObjectContract(objectType);// use Autofac to create types that have been registered with itif (_container.IsRegistered(objectType))contract.DefaultCreator = () => _container.Resolve(objectType);return contract;}} 7. Dynamic JSON ParsingOne of the features that I think is getting ever more important is the ability to serialize and deserializearbitrary JSON content dynamically - that is without mapping the JSON captured directly into a .NET typeas DataContractSerializer or the JavaScript Serializers do. Sometimes it isn't possible to map types due tothe differences in languages (think collections, dictionaries etc), and other times you simply don't have thestructures in place or don't want to create them to actually import the data.If this topic sounds familiar - you're right! I wrote about dynamic JSON parsing a few months back beforeJSON.NET was added to Web API and when Web API and the System.Net HttpClient libraries included theSystem.Json classes like JsonObject and JsonArray. With the inclusion of JSON.NET in Web API theseclasses are now obsolete and didn't ship with Web API or the client libraries. I re-linked my original post tothis one. In this post I'll discus JToken, JObject and JArray which are the dynamic JSON objects that makeit very easy to create and retrieve JSON content on the fly without underlying types. 8. Getting JSON.NETThe easiest way to use JSON.NET is to grab it via NuGet and add it as a reference to yourproject. You can add it to your project with:PM> Install-Package Newtonsoft.JsonFrom the Package Manager Console or by using Manage NuGet Packages in your projectReferences. As mentioned if you're using ASP.NET Web API or MVC 4 JSON.NET will beautomatically added to your project.Alternately you can also go to the CodePlex site and download the latest version includingsource code:http://json.codeplex.com/ 9. Apex T.G. India Pvt. LtdE-20 Sector-63,Noida -201301 (UP) INDIAPhone: (0120)- 4029000Fax: (0120)- 4029090