Converting a generic list into JSON string and then handling it in java script

  • Home
  • Blog
  • Converting a generic list into JSON string and then handling it in java script

We all know that JSON (JavaScript Object Notation) is very useful in case of manipulating string on client side with java script and its performance is very good over browsers so let’s create a simple example where convert a Generic List then we will convert this list into JSON string and then we will call this web service from java script and will handle in java script.

To do this we need a info class(Type) and for that class we are going to create generic list. Here is code for that I have created simple class with two properties UserId and UserName

public class UserInfo
{
public int UserId { get; set; }
public string UserName { get; set; }
}

Now Let’s create a web service and web method will create a class and then we will convert this with in JSON string with JavaScriptSerializer class. Here is web service class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace Experiment.WebService
{
/// 
/// Summary description for WsApplicationUser
/// 
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class WsApplicationUser : System.Web.Services.WebService
{

[WebMethod]
public string GetUserList()
{
List userList = new List();
for (int i = 1; i