Sharepoint 2013 迭代SharePoint 2013 REST API列表项
我正在使用SP 2013编写一个提供商托管的应用程序,我有一个数据层,它使用REST对sharepoint列表进行CRUD。现在我得到了JSON格式的列表项,但是我无法遍历列表数据,您能帮我吗?(是否有可反序列化为列表项的类?) 这是密码Sharepoint 2013 迭代SharePoint 2013 REST API列表项,sharepoint-2013,Sharepoint 2013,我正在使用SP 2013编写一个提供商托管的应用程序,我有一个数据层,它使用REST对sharepoint列表进行CRUD。现在我得到了JSON格式的列表项,但是我无法遍历列表数据,您能帮我吗?(是否有可反序列化为列表项的类?) 这是密码 public JToken GetListData(string webUrl, string userName, SecureString password, string listTitle) { using (va
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 Online检索数据,以下示例演示如何通过使用SharePoint REST界面: 在哪里 及
使用系统;
使用System.Collections.Generic;
Net系统;
使用System.Net.Http;
使用Newtonsoft.Json;
使用Newtonsoft.Json.Linq;
名称空间SharePoint.Client
{
公共类SPRestClient:WebClient
{
公共SPRestClient(字符串webUri)
{
BaseAddress=webUri;
FormatType=JsonFormatType.Verbose;
}
public JObject GetJson(字符串requestUri)
{
返回ExecuteJson(requestUri,HttpMethod.Get,null,默认值(字符串));
}
PublicJobject ExecuteJson(字符串请求URI、HttpMethod方法、IDictionary头、T数据)
{
字符串结果;
var uri=BaseAddress+requestUri;
如果(标题!=null)
{
foreach(headers.Keys中的var键)
{
Headers.Add(key,Headers[key]);
}
}
保证要求(方法);
开关(方法,方法)
{
案例“GET”:
结果=下载字符串(uri);
打破
案例“职位”:
如果(数据!=null)
{
var payload=JsonConvert.serialized对象(数据);
结果=上传字符串(uri、方法、方法、负载);
}
其他的
{
结果=上传字符串(uri,method.method);
}
打破
违约:
抛出新的NotSupportedException(string.Format(“方法{0}不受支持”,Method.Method));
}
返回JObject.Parse(结果);
}
私有无效保证人请求(HttpMethod方法)
{
var-mapping=newdictionary();
映射[JsonFormatType.Verbose]=“application/json;odata=Verbose”;
映射[JsonFormatType.MinimalMetadata]=“应用程序/json;odata=MinimalMetadata”;
映射[JsonFormatType.NoMetadata]=“应用程序/json;odata=NoMetadata”;
添加(HttpRequestHeader.ContentType,映射[FormatType]);
Add(HttpRequestHeader.Accept,映射[FormatType]);
if(method==HttpMethod.Post)
{
添加(“X-RequestDigest”,RequestFormDigest());
}
}
私有字符串RequestFormDigest()
{
var endpointUrl=string.Format(“{0}/_-api/contextinfo”,BaseAddress);
var result=UploadString(endpointUrl,“Post”);
var contentJson=JObject.Parse(结果);
返回contentJson[“FormDigestValue”].ToString();
}
公共JsonFormatType FormatType{get;set;}
}
公共枚举JsonFormatType
{
冗长的,
最低限度的元数据,
诺梅塔达
}
}
您需要使用DataContractJsonSerializer类来反序列化数据,如下所示: 但要使这项工作正常,您必须创建与Json结构匹配的类。最简单的方法是将原始Json响应复制到生成如下类的工具中: 您需要生成的实际类根据您在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();
}
}
public类JsonHelper
{
///JSON序列化
公共静态字符串JsonSerializer(T)
{
DataContractJsonSerializer ser=新的DataContractJsonSerializer(类型(T));
MemoryStream ms=新的MemoryStream();
ser.WriteObject(ms,t);
字符串jsonString=Encoding.UTF8.GetString(ms.ToArray());
Close女士();
返回jsonString;
}
///JSON反序列化
公共静态T JsonDeserialize(字符串jsonString)
{
DataContractJsonSerializer ser=新的DataContractJsonSerializer(类型(T));
MemoryStream ms=新的MemoryStream(Encoding.UTF8.GetBytes(jsonString));
T obj=(T)ser.ReadObject(ms);
返回obj;
}
}
//自定义Json类
公共类根对象
{
公共D{get;set;}
}
D类公共服务
{
公共GetContextWebInformation GetContextWebInformation{get;set;}
公共列表结果{get;set;}
}
公共类GetContextWebInformation
{
public int FormDigestTimeoutSeconds{get;set;}
公共字符串FormDigestValue{get;set;}
公共字符串库版本{get;set;}
公共字符串SiteFullUrl{get;set;}
公共字符串WebFullUrl{get;set;}
}
公开课成绩
{
公共ContentType ContentType{get;set;}
公共字符串EncodedAbsUrl{get;set;}
公共字符串FileLeafRef{get;set;}
公用文件夹{get;set;}
public int FileSystemObjectType{get;set;}
公共int Id{get;set;}
公共字符串ContentTypeId{get;set;}
公共字符串标题{get;set;}
public int?ImageWidth{get;set;}
公共int?图像高度{get;set;}
公共字符串ImageCreateDate{get;set;}
公共对象描述{get;set;}
公共对象关键字{get;set;}
公共字符串OData_uudlc_DocId{get;set;}
公共int ID{get;set;}
已创建公共字符串{get;set;}
聚氨基甲酸酯
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
}
}
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();
}
}