Generate JSON string output in C#


This is one of the most widely used and very useful script that you could use in your web services/ WCF services/ Handlers or any place wherein you require a JSON string to be passed to the client/ consumer.

We make use of the Serialize method in JavaScriptSerializer class in C# under the following namespace:

using System.Web.Script.Serialization;

The code snippet below show how its done:

//Namespace for the JavascriptSerializer object

using System.Web.Script.Serialization;

public string GenerateJSONString(List<myObject> myCustomList)

{

//Initialize the JavascriptSerializer object   

JavaScriptSerializer serializer = new JavaScriptSerializer();

//Initialize a stringbuilder object to hold the final JSON output     

StringBuilder jsonBuilder = new StringBuilder();

//Generate the JSON string

serializer.Serialize(myCustomList, jsonBuilder);

//Return the JSON string

return Convert.ToString(jsonBuilder);

}

This code is just a framework to get to know that the JavascriptSerializer could help you generate JSON string with ease.

In the client side, you could use jQuery.parseJSON(JSONstring); and then parse this JSON string using the myObject properties. Remeber that parseJSON was added in jQuery v1.4.1.

Basic WCF Tutorial for Beginners


I will be explaining a simple WCF service execution, using a sample project (collated from the MSDN Documentation). Lets create a Visual Studio Solution with two console application projects.
They are:
1. Service Part – Console Application
2. Client Part – Console Application
Let me take you through the Service Part:
1. Create a sample console application & Import the System. ServiceModel; & System.ServiceModel.Description; references.
2. Create an Interface with interface attribute as ServiceContract with a sample namespace for the service. This will be the Contract between the client &
the WCF service. The interface methods will have function attributes as OperationContract
// Define a service contract.
[ServiceContract(Namespace = “http://Microsoft.ServiceModel.Samples&#8221;)] //Namespace of the cs file
public interface ICalculator
{
[OperationContract]
double Add(double n1, double n2);
[OperationContract]
double Subtract(double n1, double n2);
[OperationContract]
double Multiply(double n1, double n2);
[OperationContract]
double Divide(double n1, double n2);
}
3. Define the class Calculator inheriting the Interface & implementing the 4 functionalities.
// Service class that implements the service contract.
// Added code to write output to the console window.
public class CalculatorService : ICalculator
{
public double Add(double n1, double n2)
{
double result = n1 + n2;
Console.WriteLine(“Received Add({0},{1})”, n1, n2);
Console.WriteLine(“Return: {0}”, result);
return result;
}
public double Subtract(double n1, double n2)
{
double result = n1 – n2;
Console.WriteLine(“Received Subtract({0},{1})”, n1, n2);
Console.WriteLine(“Return: {0}”, result);
return result;
}
public double Multiply(double n1, double n2)
{
double result = n1 * n2;
Console.WriteLine(“Received Multiply({0},{1})”, n1, n2);
Console.WriteLine(“Return: {0}”, result);
return result;
}
public double Divide(double n1, double n2)
{
double result = n1 / n2;
Console.WriteLine(“Received Divide({0},{1})”, n1, n2);
Console.WriteLine(“Return: {0}”, result);
return result;
}
}
4. In the main function of the Console Application, we implement the WCF service creation logic:
4.2  Create a service Host for the type as CalculatorService class & Uri as baseaddress
ServiceHost selfHost = new ServiceHost(typeof(CalculatorService), baseAddress);
4.3  Enable metadata exchanges, using ServiceMetadataBehavior from the System.ServiceModel.Description
ServiceMetadataBehavior smdb = new ServiceMetadataBehavior();
smdb.HttpGetEnabled = true;
selfHost.Description.Behaviors.Add(smdb); //Add the behavior to the servicehost
4.4  Start (and then stop) the service
selfHost.Open();
4.5 Close the service once done
Console.WriteLine(“The service is ready.”);
Console.WriteLine(“Press <ENTER> to terminate service.”);
Console.WriteLine();
Console.ReadLine();
// Close the ServiceHostBase to shutdown the service.
selfHost.Close();
Full Code (Program.cs):
using System;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Microsoft.ServiceModel.Samples
{
// Define a service contract.
[ServiceContract(Namespace = “http://Microsoft.ServiceModel.Samples&#8221;)]
public interface ICalculator
{
[OperationContract]
double Add(double n1, double n2);
[OperationContract]
double Subtract(double n1, double n2);
[OperationContract]
double Multiply(double n1, double n2);
[OperationContract]
double Divide(double n1, double n2);
}
// Service class that implements the service contract.
// Added code to write output to the console window.
public class CalculatorService : ICalculator
{
public double Add(double n1, double n2)
{
double result = n1 + n2;
Console.WriteLine(“Received Add({0},{1})”, n1, n2);
Console.WriteLine(“Return: {0}”, result);
return result;
}
public double Subtract(double n1, double n2)
{
double result = n1 – n2;
Console.WriteLine(“Received Subtract({0},{1})”, n1, n2);
Console.WriteLine(“Return: {0}”, result);
return result;
}
public double Multiply(double n1, double n2)
{
double result = n1 * n2;
Console.WriteLine(“Received Multiply({0},{1})”, n1, n2);
Console.WriteLine(“Return: {0}”, result);
return result;
}
public double Divide(double n1, double n2)
{
double result = n1 / n2;
Console.WriteLine(“Received Divide({0},{1})”, n1, n2);
Console.WriteLine(“Return: {0}”, result);
return result;
}
}
class Program
{
static void Main(string[] args)
{
// Step 1 of the address configuration procedure: Create a URI to serve as the base address.
// Step 2 of the hosting procedure: Create ServiceHost.
ServiceHost selfHost = new ServiceHost(typeof(CalculatorService), baseAddress);
try
{
// Step 3 of the hosting procedure: Add a service endpoint.
selfHost.AddServiceEndpoint(typeof(ICalculator), new WSHttpBinding(), “CalculatorService”);
// Step 4 of the hosting procedure: Enable metadata exchange.
ServiceMetadataBehavior smdb = new ServiceMetadataBehavior();
smdb.HttpGetEnabled = true;
selfHost.Description.Behaviors.Add(smdb);
// Step 5 of the hosting procedure: Start (and then stop) the service.
selfHost.Open();
Console.WriteLine(“The service is ready.”);
Console.WriteLine(“Press <ENTER> to terminate service.”);
Console.WriteLine();
Console.ReadLine();
// Close the ServiceHostBase to shutdown the service.
selfHost.Close();
}
catch (Exception ex)
{
Console.WriteLine(“An exception occurred: {0}”, ex.Message);
selfHost.Abort();
}
}
}
}
With this the Service Part is done.You can run the Project to see the service Starting up. This normally takes time to load. Now we will create a client to listen to this service.
Let me take you through the ClientPart :(Console Application in the same solution as that of the service or you can create a new solution also)
1. Create a Console Application for the ClientPart, to listen to the Service & do some computation. Add the ServiceModel reference dll.
2. Goto Visual Studio Command Prompt. Go to the directory of your client console application,
say “C:\Users\<user name>\My Documents\Visual Studio 10\Projects\Service\Client
3. Go to your Service console application & run the service.
4. Once the service is up & running, execute the svcutil.exe command like this:
svcutil.exe /language:cs /out:GeneratedProxy.cs /config:app.config http://localhost:8000/ServiceModelSamples/service
This will generate 2 files for you, the app.config (WCF configuration file) and the GeneratedProxy.cs file (the Proxy implementation of the service)
5. Import these two files to the Client console application. To view the app.config file, you need to select “All Files(*)” option in the file types.
6. Go to the Program.cs. Instantiate the  CalculatorClient (from the GeneratedProxy.cs)
Full Code (Program.cs):
using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel;
namespace ServiceModelSamples
{
class Client
{
static void Main()
{
//Step 1: Create an endpoint address and an instance of the WCF Client.
CalculatorClient client = new CalculatorClient();
// Step 2: Call the service operations.
// Call the Add service operation.
double value1 = 100.00D;
double value2 = 15.99D;
double result = client.Add(value1, value2);
Console.WriteLine(“Add({0},{1}) = {2}”, value1, value2, result);
// Call the Subtract service operation.
value1 = 145.00D;
value2 = 76.54D;
result = client.Subtract(value1, value2);
Console.WriteLine(“Subtract({0},{1}) = {2}”, value1, value2, result);
// Call the Multiply service operation.
value1 = 9.00D;
value2 = 81.25D;
result = client.Multiply(value1, value2);
Console.WriteLine(“Multiply({0},{1}) = {2}”, value1, value2, result);
// Call the Divide service operation.
value1 = 22.00D;
value2 = 7.00D;
result = client.Divide(value1, value2);
Console.WriteLine(“Divide({0},{1}) = {2}”, value1, value2, result);
//Step 3: Closing the client gracefully closes the connection and cleans up resources.
client.Close();
Console.WriteLine();
Console.WriteLine(“Press <ENTER> to terminate client.”);
Console.ReadLine();
}
}
}
Now we have both the service & the client ready in our solution.
To execute:

Step 1: Set the Service Project as the startup project & press Ctrl + F5, not F5. Ensure that the console screen says Service is up & running.
Step 2: Set the Client Project as the startup project & press Ctrl + F5. The console screen popups up with the results displayed. The service console screen
will have the status of received & returned values.
I am attaching some screenshots here to give you some heads up.
The Service Up & Running:
The Service & the Client Up & Running together:
Hope this was useful.
Special Note: This tutorial is taken from MSDN directly! But since contents were scattered across pages i just collated all of them to help readers understand the concept.