Monthly Archives: May 2012

Json.Net – serialization and deserialization APIs for Json format

Json has emerged as a new favorite data format to be sent over the wire. It is a thinner alternative to XML data format. In any integration project conversion of different data formats is the back bone of data communication. like XML Json is also compatible to any platform and easily convertible to native data types.

What is Json.Net?    It is a portable class library developed by James Newton King which helps you serialize and deserialize Json strings to .Net objects.  Once you include this library in your project you can use it’s built – in classes like  JsonConvert to serialize and deserialize objects. You can also use its Linq to Json APIs which is really helpful and will remind you of  Linq to XML.

Where do i get it from?   Download it from CodePlex.   Latest version is Json.Net 4.5. You can install it using Nuget package manager from Visual studio (10 onwards). I would recommend you to start using Nuget if you don’t have it already.

Why Json.Net?    Nobody is going to start using any new library just because it is new and sounds cool. Right?

In .Net paradigm, We already have few alternatives to serialize/deserialize json objects apart from new Json.Net.

1)      DataContract serialization                   2)  JavaScript Serialization

to read more about JavascriptSerializer for Json serialization please read my post on  JavascriptSerializer for Json

Hence, main reason why should you choose Json.Net over DataContract serializer and JavaScript Serializer   is its performance and features it provides.  There is a very useful feature comparison done among three serialization techniques . Check it out on Json.Net features comparison

In short below are the main features it provides. 

  1. Flexible JSON serializer for converting between .NET objects and JSON
  2. LINQ to JSON for manually reading and writing JSON
  3. High performance, faster than .NET’s built-in JSON serializers
  4. Write indented, easy to read JSON
  5. Convert JSON to and from XML
  6. Supports .NET 2, .NET 3.5, .NET 4, Silverlight and Windows Phone

How Json.Net can be used?       finally some code 🙂

Step 1. Download  it from CodePlex. or preferably install it using Nuget Package manager.

Step 2. Make sure your project has Newtonsoft.Json dll in your bin folder.

here, Product is a C# type.

public class Product
 {
public string Name { get; set; }
public DateTime ExpiryDate { get; set; }
public decimal Price { get; set; }
public string[] Sizes { get; set; }
 }

Converting a json string to C# product object.


public Product JsonToProductObject(string jsonString)
 {
var deserializedProduct = JsonConvert.DeserializeObject<Product>(jsonString);
return deserializedProduct;
 }

Converting product object to json fromat string.

public string ProductObjectToJson(Product product)
 {
 string json =JsonConvert.SerializeObject</strong>(product);
 return json;
 }

Linq to Json: There are instances when we do not need to serialize the objects just want to read few properties of an object or json string. Just Like Linq to XML Json.Net library also provides you the awesome capability of querying the json objects using Linq.

Below code is taken from the James.NewtonKing official website. Beauty of the code is to have the same declarative syntax that Linq users are so fond of.

List<Post> posts = GetPosts();
JObject rss =
new JObject(
new JProperty("channel",
new JObject(
new JProperty("title", "James Newton-King"),
new JProperty("link", "http://james.newtonking.com"),
new JProperty("description", "James Newton-King's blog."),
new JProperty("item",
new JArray(
from p in posts
orderby p.Title
select new JObject(
new JProperty("title", p.Title),
new JProperty("description", p.Description),
new JProperty("link", p.Link),
new JProperty("category",
new JArray(
from c in p.Categories
select new JValue(c)))))))));
// here is the output which is a json string
//{
//  "channel": {
//    "title": "James Newton-King",
//    "link": "http://james.newtonking.com",
//    "description": "James Newton-King's blog.",
//    "item": [
//      {
//        "title": "Json.NET 1.3 + New license + Now on CodePlex",
//        "description": "Annoucing the release of Json.NET 1.3, the MIT license and the source being available on CodePlex",
//        "link": "http://james.newtonking.com/projects/json-net.aspx",
//        "category": [
//          "Json.NET",
//          "CodePlex"
//        ]
//      },
//      {
//        "title": "LINQ to JSON beta",
//        "description": "Annoucing LINQ to JSON",
//        "link": "http://james.newtonking.com/projects/json-net.aspx",
//        "category": [
//          "Json.NET",
//          "LINQ"
//        ]
//      }
//    ]
//  }
//}
// Now we can query to get
var categories =  from c in rss.PropertyValue<JObject>("channel")                                                          .PropertyValue<JArray>("item")                                                                            .Children<JObject>()                                                                                      .PropertyValues<JArray>("category")                                                                       .Children<string>()                                                                                       group c by c into g                                                                                       orderby g.Count() descending                                                                              select new { Category = g.Key, Count = g.Count() };
foreach (var c in categories)                                                                             {
Console.WriteLine(c.Category + " - Count: " + c.Count);                                                  }
// below is the output
//Json.NET - Count: 2
//LINQ - Count: 1
//CodePlex - Count: 1

To understand the Json.Net library in detail, you can refer to the official Json.Net classes and APIs reference.

James Newton King had really made our lives easy with this cool library which is not only new but performs great when compared to existing serialization techniques. Hats off to him 🙂

Note: Examples and features are cited from the original json.Net website http://james.newtonking.com/

Advertisements

Custom paging query comparison Sql server 2000 , 2005 and 2012 (denali)

Custom paging is a very common requirement for any web application. It was always performance enhancer for our old applications. Linq and generic collections enabled us to process and query the result sets in memory. However, if the query can fetch only desired number of records with a better query performance, we need not perform any manipulation later on.

I am going to describe the custom paging query which had evolved with every Sql server upgrade. I will compare Sql Server 2000, 2005 and 2012 (denali) version to showcase the performance improvement. Sample DB isAdventureWorks.

Sql Server 2000: In 2000 we had to create a temp table before we skip certain number of records and fetch required number of records only. Temp table creation and inner join degrades the query performance here.


CREATE PROCEDURE GetPersonPaged_Sql2000
(
@startRowIndex int,
@pageSize int
)
AS
BEGIN
 SET NOCOUNT ON;

DECLARE @lastRowIndex int

SET @lastRowIndex = (@startRowIndex + @pageSize) - 1;

--Create a table variable
 DECLARE @TempItems TABLE
 (
 ID int IDENTITY,
 BusinessEntityID int,
 firstname varchar(200),
 MiddleName varchar(200)
 )
 -- Insert the rows from tblItems into the temp. table
 INSERT INTO @TempItems (BusinessEntityID,firstname,MiddleName)
 SELECT BusinessEntityID,firstname,MiddleName FROM Person.Person
 order by BusinessEntityID

-- Now, return the set of paged records
 SELECT p.* FROM @TempItems t
 INNER JOIN Person.Person p ON
 p.BusinessEntityID = t.BusinessEntityID
 WHERE ID BETWEEN @startRowIndex AND @lastRowIndex
 order by BusinessEntityID

END

Sql Server 2005: With Ranking functions introduced in 2005 upgrade it was easier to get a row number for each record (Please note that Sql Server never had any keyword RowNum like Oracle). ROW_NUMBER() is the function which helps sorting and numbering any result set. Please refer to http://msdn.microsoft.com/en-us/library/ms186734.aspx to know more about this function.
New implementation was even better using Common table expression CTE. Refer http://msdn.microsoft.com/en-us/library/ms190766.aspxto read more about CTE.

CREATE PROCEDURE GetPersonPaged_Sql2005
(
@startRowIndex int,
@pageSize int
)
AS
BEGIN
 SET NOCOUNT ON;
 DECLARE @lastRowIndex int

SET @lastRowIndex = (@startRowIndex + @pageSize) - 1;

;with CTE
 AS
 (
 select BusinessEntityID,firstname,MiddleName , ROW_NUMBER() OVER (order by BusinessEntityID ) as rownum
 from Person.Person
 )
 select * from CTE
 where rownum between @startRowIndex AND @lastRowIndex

END

It had improved the query performance by more than 80% than the Sql 2000 query. You can test the same by comparing execution plans.
Finally the winner is :

Sql Server 2012:It introduced new keywords like OFFSET and ROWS. It not only reduces the number of lines of code but improve the query performance by more than 50% when compared to Sql 2005 query using CTE.


CREATE PROCEDURE GetPersonPaged_Sql2012
(
@startRowIndex int,
@pageSize int
)
AS
BEGIN
 SET NOCOUNT ON;
 DECLARE @lastRowIndex int

SET @lastRowIndex = (@startRowIndex + @pageSize) - 1;

SELECT * FROM Person.Person
 ORDER BY BusinessEntityID
 OFFSET @startRowIndex ROWS
 FETCH NEXT @lastRowIndex ROWS ONLY;

END

Conclusion:    2012 query is the best of all three in terms of ease, lines of code and performance. If you are still using the old style query(even after upgrading to next version of sql server) for custom paging, this is high time you should switch to query with new syntax which is best suited for that particular version.

Note: I did not cover Sql server 2008 as it did not add any features which could add any value to custom paging querying.

I hope it is useful!