Share via


SharePoint - Converting to JSON

The below code is valid for SharePoint 2013/2016.

Hopefully, things are better in SharePoint 2016 to read data from external domain and get the results in JSON which can be used for various purposes. A reference to SharePoint.Client and System.Web.Extentions need to be added. Below are two codes, one to convert a data to JSON and the other code to read SharePoint list and return in JSON format.

Code 1: Read data and convert to JSON

//References::http://stackoverflow.com/questions/6201529/turn-c-sharp-object-into-a-json-string-in-net-4 //https://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx namespace MSDNJsonData

{ class 

{ int year;

int month;

int day;

} class 

{ string firstName;

string lastName;

MyDate dateOfBirth;

} Program

static string[] args)

{ new 

{ firstName = ,

lastName = ,

dateOfBirth = MyDate

var json = JavaScriptSerializer().Serialize(obj);

Console.Read();

} } }

Code 2: To read SharePoint and return data in JSON format.

using ServiceReference1;

class 

{ string Title;

} class 

{ string Email;

string MailGroup;//A lookup column

} Program

static string[] args)

{ http://xxx.sharepoint.com;

ServiceReference1.new ServiceReference1.new "/_vti_bin/listdata.svc"));

context.Credentials = System.Net.// Starting with ClientContext, the constructor requires a URL to the

// server running SharePoint.

ClientContext clientcontext = ClientContext(websiteUrl);

List announcementsList = clientcontext.Web.Lists.GetByTitle();

// so that it grabs all list items, regardless of the folder they are in.

CamlQuery query = ListItemCollection items = announcementsList.GetItems(query);

clientcontext.Load(items); clientcontext.ExecuteQuery(); ListItem listItem // We have all the list item data. For example, Title.

Console.WriteLine(listItem[]);

new 

{ Title = listItem[].ToString()

}; new Console.WriteLine(json);

}

List emailList = clientcontext.Web.Lists.GetByTitle();

// so that it grabs all list items, regardless of the folder they are in.

CamlQuery query2 = ListItemCollection items2 = emailList.GetItems(query);

clientcontext.Load(items2); clientcontext.ExecuteQuery(); ListItem listItem2 // We have all the list item data. For example, Title.

Console.WriteLine(listItem2[]);

"MailGroup"] FieldLookupValue;

new 

{ Email = listItem2[].ToString(),

MailGroup = mail.LookupValue }; new Console.WriteLine(json2);

}