1
votes

I am writing a Provider Hosted APP using SP 2013 and I have a data layer which uses REST to CRUD on sharepoint lists. Now I got the List items in JSON format but I am not able to iterate through the list data can you please help in doing that? (is there any class for List Items which I can deserialize into?)

This is the code

public JToken GetListData(string webUrl, string userName, SecureString password, string listTitle)
        {
            using (var client = new WebClient())
            {
                client.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
                client.Credentials = new SharePointOnlineCredentials(userName, password);
                client.Headers.Add(HttpRequestHeader.ContentType, "application/json;odata=verbose");
                client.Headers.Add(HttpRequestHeader.Accept, "application/json;odata=verbose");
                var endpointUri = new Uri(new Uri(webUrl), string.Format("/sites/DTF/_api/web/lists/getbytitle('{0}')/Items", listTitle));
                var result = client.DownloadString(endpointUri);
                var t = JToken.Parse(result);
                return t["d"];
            }
        }
2

2 Answers

1
votes

You need to use the DataContractJsonSerializer class to deserialize the data as is demonstrated here:

http://www.codeproject.com/Articles/272335/JSON-Serialization-and-Deserialization-in-ASP-NET

To make this work though you have to create classes that match the structure of the Json. The easiest way to do this copying a raw Json response into a tool which will generate the classes like this one:

http://json2csharp.com/

The actual classes you will need to generate varies based on the structure of the data you are getting in your REST response. Here is an example I created that demonstrates making a request, parsing the Json Response and downloading a file based on the result:

public class JsonHelper
{
    /// JSON Serialization
    public static string JsonSerializer<T>(T t)
    {
        DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
        MemoryStream ms = new MemoryStream();
        ser.WriteObject(ms, t);
        string jsonString = Encoding.UTF8.GetString(ms.ToArray());
        ms.Close();
        return jsonString;
    }
    /// JSON Deserialization
    public static T JsonDeserialize<T>(string jsonString)
    {
        DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
        MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
        T obj = (T)ser.ReadObject(ms);
        return obj;
    }
}

//Custom Json Classes
public class RootObject
{
    public D d { get; set; }
}
public class D
{
    public GetContextWebInformation GetContextWebInformation { get; set; }
    public List<Result> results { get; set; }
}
public class GetContextWebInformation
{
    public int FormDigestTimeoutSeconds { get; set; }
    public string FormDigestValue { get; set; }
    public string LibraryVersion { get; set; }
    public string SiteFullUrl { get; set; }
    public string WebFullUrl { get; set; }
}
public class Result
{
    public ContentType ContentType { get; set; }
    public string EncodedAbsUrl { get; set; }
    public string FileLeafRef { get; set; }
    public Folder Folder { get; set; }
    public int FileSystemObjectType { get; set; }
    public int Id { get; set; }
    public string ContentTypeId { get; set; }
    public string Title { get; set; }
    public int? ImageWidth { get; set; }
    public int? ImageHeight { get; set; }
    public string ImageCreateDate { get; set; }
    public object Description { get; set; }
    public object Keywords { get; set; }
    public string OData__dlc_DocId { get; set; }     
    public int ID { get; set; }
    public string Created { get; set; }
    public int AuthorId { get; set; }
    public string Modified { get; set; }
    public int EditorId { get; set; }
    public object OData__CopySource { get; set; }
    public int? CheckoutUserId { get; set; }
    public string OData__UIVersionString { get; set; }
    public string GUID { get; set; }
}

//SharePoint Calls
class Program
{
    static void Main()
    {
        string url = "https://sharepoint.wilsonconst.com/";
        string filename = "2010-07-23 13.32.22.jpg";
        string digest = "";
        HttpClient client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true });
        client.BaseAddress = new System.Uri(url);
        string cmd = "_api/contextinfo";
        client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");
        client.DefaultRequestHeaders.Add("ContentType", "application/json");
        client.DefaultRequestHeaders.Add("ContentLength", "0");
        StringContent httpContent = new StringContent("");
        HttpResponseMessage response = client.PostAsync(cmd, httpContent).Result;
        if (response.IsSuccessStatusCode)
        {
            string content = response.Content.ReadAsStringAsync().Result;
            RootObject sp = JsonHelper.JsonDeserialize<RootObject>(content);
            digest = sp.d.GetContextWebInformation.FormDigestValue;
        }
        client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true });
        client.BaseAddress = new System.Uri(url);
        client.DefaultRequestHeaders.Clear();
        client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");
        client.DefaultRequestHeaders.Add("X-RequestDigest", digest);
        client.DefaultRequestHeaders.Add("X-HTTP-Method", "GET");
        string uri = "_api/web/lists/GetByTitle('Wilson Pictures')/Items?$select=ID,FileLeafRef,EncodedAbsUrl&$filter=FileLeafRef eq '" + filename + "'";
        HttpResponseMessage response2 = client.GetAsync(uri).Result;
        response2.EnsureSuccessStatusCode();
        if (response2.IsSuccessStatusCode)
        {
            string listItems = response2.Content.ReadAsStringAsync().Result;
            RootObject sp = JsonHelper.JsonDeserialize<RootObject>(listItems);
            foreach (Result result in sp.d.results)
            {
                MemoryStream stream = (MemoryStream)client.GetAsync(result.EncodedAbsUrl).Result.Content.ReadAsStreamAsync().Result;
                using(FileStream fileStream = System.IO.File.Create(@"C:\" + result.FileLeafRef))
                {
                    stream.WriteTo(fileStream);
                }
            }
        }
        else
        {
            var content = response.Content.ReadAsStringAsync();
        }
    }

This seems like a lot of complexity, but really it makes working with Json objects quite easy and takes only moments to setup before you can start calling your custom objects to easily manipulate the data.

0
votes

Assuming that you want to retrieve data from SharePoint Online the following example demonstrates how to consume SharePoint REST Interface via WebClient Class:

using (var client = new SPRestClient(webUri.ToString()))
{
    client.Credentials = GetCredentials(webUri,userName,password);
    client.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
    var data = client.GetJson("/_api/lists/getbytitle('Tasks')/items"); //get list items 
    //print list item's title 
    foreach (var item in data["d"]["results"])
    {
        Console.WriteLine(item["Title"]);
    }
}

where

public static SharePointOnlineCredentials GetCredentials(Uri webUri, string userName, string password)
{
    var securePassword = new SecureString();
    foreach (var ch in password) securePassword.AppendChar(ch);
    return  new SharePointOnlineCredentials(userName, securePassword);
}

and

using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace SharePoint.Client
{
    public class SPRestClient : WebClient
    {
        public SPRestClient(string webUri)
        {
            BaseAddress = webUri;
            FormatType = JsonFormatType.Verbose;
        }

        public JObject GetJson(string requestUri)
        {
            return ExecuteJson(requestUri, HttpMethod.Get, null, default(string));
        }

        public JObject ExecuteJson<T>(string requestUri, HttpMethod method, IDictionary<string, string> headers, T data)
        {
            string result;
            var uri = BaseAddress + requestUri;
            if (headers != null)
            {
                foreach (var key in headers.Keys)
                {
                    Headers.Add(key, headers[key]);
                }     
            }

            EnsureRequest(method);
            switch (method.Method)
            {
                case "GET":
                    result = DownloadString(uri);
                    break;
                case "POST":
                    if (data != null)
                    {
                        var payload = JsonConvert.SerializeObject(data);
                        result = UploadString(uri, method.Method, payload);
                    }
                    else
                    {
                        result = UploadString(uri, method.Method);
                    }
                    break;
                default:
                    throw new NotSupportedException(string.Format("Method {0} is not supported", method.Method));
            }
            return JObject.Parse(result);
        }


        private void EnsureRequest(HttpMethod method)
        {
            var mapping = new Dictionary<JsonFormatType, string>();
            mapping[JsonFormatType.Verbose] = "application/json;odata=verbose";
            mapping[JsonFormatType.MinimalMetadata] = "application/json; odata=minimalmetadata";
            mapping[JsonFormatType.NoMetadata] = "application/json; odata=nometadata";
            Headers.Add(HttpRequestHeader.ContentType, mapping[FormatType]);
            Headers.Add(HttpRequestHeader.Accept, mapping[FormatType]);
            if (method == HttpMethod.Post)
            {
                Headers.Add("X-RequestDigest", RequestFormDigest());
            }
        }



        private string RequestFormDigest()
        {
            var endpointUrl = string.Format("{0}/_api/contextinfo", BaseAddress);
            var result = UploadString(endpointUrl, "Post");
            var contentJson = JObject.Parse(result);
            return contentJson["FormDigestValue"].ToString();
        }



        public JsonFormatType FormatType { get; set; }

    }

    public enum JsonFormatType
    {
        Verbose,
        MinimalMetadata,
        NoMetadata
    }
}

SPRestClient.cs