Sunday, June 12, 2016

REST response return type as XML/JSON

Retrieving SharePoint site resources using REST with response formats in JSON and XML.
[code]using Microsoft.SharePoint.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using System.Xml.Linq;

namespace ConsoleApplication9
{
    class Program
    {
        static void Main(string[] args)
        {
            restXML();
            restJSON();         
        }

        private static void restJSON()
        {
            var url = "http://sharepoint2013.gcm.com/sites/RBSSharePoint/_api/web";
            var client = new WebClient();
            client.UseDefaultCredentials = true;
            var xml = client.DownloadString(url);
            var doc = XDocument.Parse(xml);
            XNamespace ds = "http://schemas.microsoft.com/ado/2007/08/dataservices";
            var titles = doc.Descendants(ds + "Title");
            var title = titles.First().Value;
            Console.WriteLine(title);
        }

        private static void restXML()
        {
            var url = "http://sharepoint2013.gcm.com/sites/RBSSharePoint/_api/web";
            var client = new WebClient();
            client.UseDefaultCredentials = true;
            client.Headers[HttpRequestHeader.Accept] = "application/json;odata=verbose";
            var json = client.DownloadString(url);
            var ser = new JavaScriptSerializer();
            dynamic item = ser.Deserialize<object>(json);
            Console.WriteLine(item["d"]["Title"]);
            Console.ReadLine();

        }
    }
}[/code]

No comments:

Post a Comment