Blog Archives

Json data – Thinner and familiar data format

I have written a little about json in bits and pieces in my erlier posts but moving further i felt a strong urge to put it altogether about Json. Mainly from development perspective which should cover from basic syntax to serialization and desrialization of json data. It also consists of links to good articels wherever needed.

Json (Javascript object notation) is a data format which is a thinner and cleaner than xml/soap formats. I am putting main points here that can get you started right away. Please refer to W3Schools on Json for the detailed syntax.

  • Data is in name/value pairs
  • Data is separated by comma
  • Json values can be integer,floating point,string(in double quotes),boolean (true/false),Array (square brackets), object(curly brackets) or NULL

Mostly we deal with object oriented way of representation so let me take an example.

Employee.cs it is a c# class.


public class Employee{

public string Name {get;set;}

public int      Age    {get;set;}

public bool   IsPermanent {get; set;}

Json representation of an Employee object:


// single object of an employee

{"Name" : "praveen" , "Age" : 30, "IsPermanent" : true }

// list or array of employees. please note the square brackets.

var employeesArray = [

{ "Name" : "praveen"   , "Age" : 30 ,"IsPermanent" : true} ,

{ "Name" : "amit"      , "Age" : 27 ,"IsPermanent" : false} ,

{ "Name" : "sudhakar"  , "Age" : 27 ,"IsPermanent" : true}

]

Now that you must be comfortable with the syntax of Json data. next step is to understand how to handle Json data effectively.In this post i will discuss how to consume a webapi http service which returns an object in Json data format.

Note: To create WebApi service please refer to My Post on How to create a WebApi

Let us see few jquery methods we can use to fetch Json data.

Using $.ajax(type,uri,onSuccessMethod,onErrorMethod): .ajax() is much familiar method as it is more generic in nature and can call “Get”, “Post” etc. type of requests. you can also specify content type (default is xml).


function find() {
var id = $('#empId').val();
var httpApiUri = "api/employees/" + id;
$.ajax (
type   :  "GET",
url     :   httpApiUri ,
contentType : "json",

success  : function(data){
              $.each(data, function (index,item){
               $("#employeestable").append("<tr><td>" + item.FirstName + "</td>" + "<td>" + item.LastName + "</td>");
              });
           },
error   :  function (jqXHR, textStatus, err) {
             alert('Error: ' + err);
           });
);
}

Using $.getJSON(uri,successmethod): Unlike $.ajax() method this one is specific to “Get” type of requests and fetch the data in Json format by default which is great if you are sure of your data format beforehand.

function find() {
var id = $('#empId').val();
var httpApiUri = "api/employees/" + id;
$.getJSON ( httpApiUri , function(data){
                         $.each(data, function (index,item){
                               $("#employeestable").append("<tr><td>" + item.FirstName + "</td>" + "<td>" + item.LastName + "</td>");
                               });
                         }
          )
          .fail( function (jqXHR, textStatus, err) {
              alert('Error: ' + err);
           });
}

How to send the json data as a parameter?
Now that you know how to represent Json data using javascript notation and jquery syntax.Next step is to serialize your normal data say a javascript variable and send it as a parameter to a webapi service for instance. I am considering Jquery as an example here as it is the most widely acceptable cross browser javascript library. There are various jquery apis available to achieve this.

Using JSON.stringify( jsonData ):  Let’s say i want to make a “post” request to add an employee using an http service. you can use JSON.stringify() method which is available on Json2.js on GitHub.You need to include this js file in your code. This method will serialize your javascript variable into json format and send it over the wire.

Note: One important thing about $.ajax() method is that the parameters contentType  is a format which is returned on success of the call. data  is the parameter which defines datatype of the parameter you are sending to the service. both in this example are json.


<script type="text/javascript">

$("#btnInsert").click( function() {

var empObj ='{ "FirstName" : "Praveen"   , "LastName" : "Saxena"}' ;

$.ajax({

type: 'POST',
url: 'http://serverName:portNo/Employees/PostEmployee',
data: <strong>JSON.stringify(empObj </strong><strong>)</strong>,
contentType: 'application/json',
processData: true,
success: function (result) {
$('#results').html('Result: ' + JSON.stringify(result));
},
error: function (xhr, status, error) {
$('#results').html('Error: ' + xhr.responseText);
}
});

}
</script>


Using jQuery.ParseJSON(jsonData):
This method is added in jquery version -1.4.1 onwards so you dont need to include any other js file. It performs the similar operation.


<script type="text/javascript">

$("#btnInsert").click( function() {

var empObj ='{ "FirstName" : "Praveen"   , "LastName" : "Saxena"}' ;

$.ajax({

type: 'POST',
url: 'http://serverName:portNo/Employees/PostEmployee',
data: <strong>jQuery.parseJSON(empObj </strong><strong>)</strong>,
contentType: 'application/json',
processData: true,
success: function (result) {
$('#results').html('Result: ' + JSON.stringify(result));
},
error: function (xhr, status, error) {
$('#results').html('Error: ' + xhr.responseText);
}
});

}
</script>

Deserializing JSON data: Now that you know 1) Json syntax 2) jquery apis to send json data as parameter, we need to know how to deserialize the json data at code side. We have several ways to do it.
I found Json.net library very easy to use and i have a detailed post dedicated to JSON.Net. Please refer to  My Post on Json.Net to serialize an deserialize Json data

Now if you are given your next task on jquery with services dealing with json data, i guess you are good to go 🙂 (or at least googled code will start making sense if you are not fully prepared)

Hope it helps!

Praveen

 

Advertisements

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/

Converting a Json string to C# object using JavaScriptSerializer

Gradually web development is shifting it’s focus to Client side programming day by day. Json is simply a Fat Free alternative to XML. Earlier XML was our commonly accepted data format across all the platforms, but JSON seems to be even more promising because of it’s light weight and familiar syntax (reminds me of .Net  object initializer).   Jquery on the other hand has become a standard which has excellent support with JSON format.

Let’s say we have a C# class Product.


class Product {

int ProductID;

string ProductName;

int CategoryID;

int SupplierID;

decimal UnitPrice;

}

JSON string example : We need to make sure our json string syntax is correct.  Class property names should be same to map it by default.

Here is the syntax

“{Property1 : ‘stringvalue’ , Property2 : ‘stringValue2’, Property3 : 123 }”

var jsonProductString = "{ ProductID :" + pid + ", ProductName :'" + pName + "',CategoryID :" + categoryId + ", SupplierID :" + supplierId + ", UnitPrice :" + unitPrice + "}";

Conversion to C# object: this is code is tested in .Net4.0.


System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

 var p = serializer.Deserialize<Product>(args);
// p is Product object initialized with Json string values.

Interesting part is after deserialization all the data types are easily mapped to Product class data types

Update:  There is a new serialization technique which performs even better for Json serialization. It is Json.Net library developed by James Newton King. it is available on codeplex.

Read more about Json.Net library on my Post on Json.Net library.
I hope it will be useful!!