Friday 4 December 2009

How to Use JSON in JavaScript and .NET?

It's very easy to use JSON, believe me!

JSON is a lightway format of sending messages from one place to another.

From JavaScript:

Use JavaScriptSerializer class to serialize into JSON and deserialize from JSON:


To use this you should add ScriptManager on your aspx page.

Examples: ...

From .NET 3.5 and above:

1) Use JavaScriptSerializer class:

This class is located in System.Web.Extensions.dll.

2) Use DataContractJsonSerializer class:

This class in located in System.ServiceModel.Web.dll.

DataContractJsonSerializer Example:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;


namespace CompanyName.ApplicationName.Model
{
[Serializable]
public class CMMessage
{
public string ClientIndividual;


public string JobFunction;


public string LastTeamActivity;


public string ClientCompany;


public List CMPhoneList;


///
/// This method is responsible to json serialize this object
///
///
public string ToJson()
{
var serializer = new DataContractJsonSerializer(typeof (CMMessage));
using (var memoryStream = new MemoryStream())
{
serializer.WriteObject(memoryStream, this);
return Encoding.Default.GetString(memoryStream.ToArray());
}
}


///
/// This method is responsible to deserialize a json text to a CMMessage object
///
/// json text
///
public static CMMessage GetByJson(string json)
{
var serializer = new DataContractJsonSerializer(typeof(CMMessage));
using (var memoryStream = new MemoryStream(Encoding.Default.GetBytes(json)))
{
return serializer.ReadObject(memoryStream) as CMMessage;
}
}


}
}






From .NET 2.0:

I am afraid Microsoft didn't create any class for JSON Serialization in .NET 2.0, however, there are some workarounds for you:

1) Use http://json.codeplex.com/

2) Create your own JSONSerializer for .NET 2.0 using .NET Reflector on either JavaScriptSerializer class or DataCotnractJsonSerializer class in .NET 3.5:

http://geekswithblogs.net/Mochalogic/articles/103330.aspx

More resources:
  • http://msdn.microsoft.com/en-us/library/bb299886.aspx

No comments: