1

I want to create a WebService that returns the SharePoint ListCollection in JSON format. I have tried by using following code:

ClientContext ctx = new ClientContext("mySite");
ctx.Credentials = new System.Net.NetworkCredential(userId, password, domain);
Web w = ctx.Web;
ctx.Load(w);
ctx.ExecuteQuery();

ListCollection listColl = w.Lists;
ctx.Load(listColl);
ctx.ExecuteQuery();

DataContractJsonSerializer serializer = new DataContractJsonSerializer(listColl.GetType());
//create a memory stream
MemoryStream ms = new MemoryStream();
//serialize the object to memory stream
serializer.WriteObject(ms, listColl);
//convert the serizlized object to string
string jsonString = Encoding.Default.GetString(ms.ToArray());
//close the memory stream
ms.Close();

return jsonString;

But it gives me Error like follows:

System.Runtime.Serialization.InvalidDataContractException: Type 'Microsoft.SharePoint.Client.ListCollection' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute. See the Microsoft .NET Framework documentation for other supported types.

1

I am curious - why do this instead of using the ListData.svc that already returns the lists in XML or JSON format already? Including data from individual lists if you desire and the ability to query against them? See Using the REST Interface for more infomation: http://msdn.microsoft.com/en-us/library/ff798339.aspx

Example jQuery:

$.getJSON(L_Menu_BaseUrl + "/_vti_bin/ListData.svc", function(d) {
  // do something with the returned data
})

The raw JSON will look something like this:

{
  "d" : {
    "EntitySets": [ "Attachments", "Documents", "Images", "UserInformationList" ]
  }
}

Pro-tip: L_Menu_BaseUrl is a global variable that contains the server relative path to your current site. e.g. /sites/TeamSite

  • Yes you are right. But I need to create a web service that needs to call by client and then as par the clients requirement I need to return proper object of SharePoint. – Rahul Gokani Oct 4 '13 at 4:15
  • What do you mean "proper object of SharePoint"? – Goyuix Oct 4 '13 at 18:08
  • Proper object means the particular object of the SharePoint. If client request for particular list web service need to return that list object only. – Rahul Gokani Oct 5 '13 at 4:25
  • The ListData.svc can return just a single item from a list as well: ListData.svc/Documents(1) would return the metadata for the SPListItem with ID of 1 from the Documents library for example. Does that cover your need of a "proper object"??? – Goyuix Oct 7 '13 at 23:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.