【问题标题】:Iterating through SharePoint 2013 REST API List Items遍历 SharePoint 2013 REST API 列表项
【发布时间】:2016-01-08 15:48:12
【问题描述】:

我正在使用 SP 2013 编写一个提供程序托管的应用程序,并且我有一个数据层,它在共享点列表上使用 REST 到 CRUD。现在我得到了 JSON 格式的列表项,但我无法遍历列表数据,你能帮忙吗? (有没有可以反序列化的 List Items 类?)

这是代码

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"];
            }
        }

【问题讨论】:

    标签: sharepoint-2013


    【解决方案1】:

    您需要使用 DataContractJsonSerializer 类来反序列化数据,如下所示:

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

    要完成这项工作,您必须创建与 Json 的结构匹配的类。最简单的方法是将原始 Json 响应复制到一个工具中,该工具将生成类似这样的类:

    http://json2csharp.com/

    您需要生成的实际类会根据您在 REST 响应中获得的数据结构而有所不同。这是我创建的一个示例,它演示了发出请求、解析 Json 响应并根据结果下载文件:

    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();
            }
        }
    

    这看起来很复杂,但实际上它使使用 Json 对象变得非常容易,并且只需片刻即可开始调用自定义对象以轻松操作数据。

    【讨论】:

    • 只是徘徊,OP 到底在哪里询问使用 HttpClient 类以及为什么有人需要同时使用 HttpClient 和 WebClient?.. 还有一点,IMO 引入这些自定义是非常糟糕的建议Json 类,这些 Deferred* 属性有什么用处?
    • 更新了我的答案以删除由 Json2CSharp 创建的不必要的细节和类,并仅使用 HttpClient。
    【解决方案2】:

    假设您要从 SharePoint Online 中检索数据,以下示例演示了如何通过 WebClient Class 使用 SharePoint REST 接口:

    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"]);
        }
    }
    

    在哪里

    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);
    }
    

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-11-30
      • 2014-11-21
      • 1970-01-01
      • 2014-04-26
      • 1970-01-01
      • 2013-06-06
      • 2020-10-02
      相关资源
      最近更新 更多