Generating a JSON string object on the server side can be
easily done by using a StringBuilder object and appending the objects’
properties into the instance of the StringBuilder. For instance, you convert a
C# object into string JSON string object as follows:
Listing 7
public class Person
{
#region Member fields
int id = - 1;
string name = "";
#endregion
#region Properties
public int ID
{
get
{
return this.id;
}
set
{
this.id = value;
}
}
public string Name
{
get
{
return this.name;
}
set
{
this.name = value;
}
}
#endregion
#region Constructors
public Person(): this( - 1, ""){}
public Person(int id, string name)
{
this.id = id;
this.name = name;
}
#endregion
}
// Create a new instance of Person object
Person p = new Person(5, "Bilal Haidar");
// Construct the JSON string object
StringBuilder sb = new StringBuilder();
sb.Append("{");
sb.AppendFormat("\"{0}\": \"{1}\"", p.ID, p.Name);
sb.Append("}");
Response.Write(sb.ToString());
You can see how easy it is to convert your business objects
to JSON string objects. You just need to follow the JSON format and you are
there!
If you had more complicated objects they might include arrays
of objects or simple values. It is not wise to do the conversion yourself in a
manual way. Therefore, I will guide you to a great JSON DLL that is called Jason.NET.
An example of how you can utilize the Jason.NET to get a
JSON string object is shown in the listing below.
Listing 8
// create a new instance of the Person object
Person p = new Person(5, "Bilal Haidar");
// Convert the C# object into a JSON string object.
string jsonStringObj = JavaScriptConvert.SerializeObject(p);
// Show the output which shall be something as:
// {"ID":5,"Name":"Bilal Haidar"}
Response.Write(jsonStringObj);
You can see and feel how easy it is to use the JavaScriptConvert
object to get your JSON string objects from the C# objects.
I will not go into details on how to use the Json.NET DLL.
You can visit its site to get more tutorials on how to use this helpful DLL
when generating JSON data.