How to build JSON endpoints in SharePoint 2010 as a way to expose SPList items
I have been frequently asked by my friends (mainly, front-end designers/developers) a simple way to expose SPList items in json format. Initially, I thought there is a built-in class to expose data in json format, but I could not find anything in MSDN. I had no choice but to build a custom module in SharePoint 2010. Surprisingly, the task was very simple, and I did not have to use any third-party json libraries (e.g., json.net) although SharePoint 2010 only supports .NET 3.5. Let's get started.
First, I am going to use a tool called SPMetal (built-in SharePoint tool) to generate entity classes, which provide an OOP interface to the SPList content. For example, I want to expose SPList in my sub-site called "forms". In order to generate stub codes, I need to issue the following command:
C:\mystubcodes>spmetal /web:http://mysharepoint/forms /code:forms.cs
Now I am going to create a SharePoint 2010 application page project.
1. Create a empty SharePoint project in Visual Studio 2010
2. Add Application Page (GetForms.aspx) to the project.
3. Add forms.cs into the project.
4. Add the following references.
using Microsoft.SharePoint.Linq;
using System.Linq;
using System.Web.Script.Serialization;
5. Change the base class of your main class as shown below. The main class (in my case, GetForms) should inherit UnsecuredLayoutsPageBase to allow anonymous access. In addition, override AllowAnonymousAccess as show below.
namespace SharePointApplications.Layouts.JsonWS
{
public partial class GetForms : UnsecuredLayoutsPageBase
{
protected override bool AllowAnonymousAccess
{
get
{
return true;
}
}
First, I am going to use a tool called SPMetal (built-in SharePoint tool) to generate entity classes, which provide an OOP interface to the SPList content. For example, I want to expose SPList in my sub-site called "forms". In order to generate stub codes, I need to issue the following command:
C:\mystubcodes>spmetal /web:http://mysharepoint/forms /code:forms.cs
Now I am going to create a SharePoint 2010 application page project.
1. Create a empty SharePoint project in Visual Studio 2010
2. Add Application Page (GetForms.aspx) to the project.
3. Add forms.cs into the project.
4. Add the following references.
using Microsoft.SharePoint.Linq;
using System.Linq;
using System.Web.Script.Serialization;
5. Change the base class of your main class as shown below. The main class (in my case, GetForms) should inherit UnsecuredLayoutsPageBase to allow anonymous access. In addition, override AllowAnonymousAccess as show below.
namespace SharePointApplications.Layouts.JsonWS
{
public partial class GetForms : UnsecuredLayoutsPageBase
{
protected override bool AllowAnonymousAccess
{
get
{
return true;
}
}
...
6. Add the following codes in Page_Load function. DataFetch function (which will be explained later in details) takes two parameters, one for the site URL and another for the List name, and returns the json string that contains the list of items in SPList (Forms). Then, it clears all content output from the buffer stream, checks whether the caller is from another domain or not (jsonp), sets the content type and finally writes the json string to the current HTTP output.
protected void Page_Load(object sender, EventArgs e)
{
string callback;
string json;
json = DataFetch(SPContext.Current.Site.RootWeb.Url + "/forms", "Forms");
Response.Clear();
if (Request.QueryString["callback"] == null)
if (Request.QueryString["callback"] == null)
{
Response.ContentType = "application/json; charset=utf-8";
Response.Write(json);
}else{
callback = Request.QueryString["callback"];
Response.ContentType = "application/x-javascript; charset=utf-8";
Response.Write(string.Format("{0}({1});", callback, json));
}
Response.End();
}
7. Create a class called "FormNode".
namespace SharePointApplications.Layouts.JsonWS
{
class FormNode
{
public int Id { get; set; }
public string FormID { get; set; }
public string Title { get; set; }
}
}
8. Create a JSON helper class which serializes the list of objects into json format. Make sure to add System.Web.Script.Serialization reference.
using System.Web.Script.Serialization;
namespace SharePointApplications.Layouts.JsonWS
{
public static class JSONHelper
{
public static string ToJSON(this object obj)
{
JavaScriptSerializer s = new JavaScriptSerializer();
return s.Serialize(obj);
}
public static string ToJSON(this object obj, int recursionDepth)
{
JavaScriptSerializer s = new JavaScriptSerializer();
s.RecursionLimit = recursionDepth;
return s.Serialize(obj);
}
}
}
9. Finally, create a function called DataFetch. This function retrieves data from SPList and formats them in json format.
protected string DataFetch(string url, string listname)
{
string json="";
try
{
using (DataContext data = new DataContext(url))
{
EntityList forms = data.GetList(listname);
var retforms = from form in forms
orderby form.FormID
select new FormNode
{
Id = (int)form.Id,
FormID = form.FormID,
Title = form.Title,
};
json = retforms.ToList().ToJSON();
}
}
}catch{
json = @"[{""error"" : ""Failed while accessing Form Library""}]";
}
return json;
}
}
Comments
Post a Comment