如何在C#控制台应用中将JSON转为变量并导入SharePoint列表
没问题,我来一步步帮你搞定把750+家公司的JSON数据上传到SharePoint列表的流程——核心就是把JSON反序列化成可操作的C#对象,再结合你已有的SharePoint上传逻辑批量处理就行,咱们拆解来看:
1. 创建匹配JSON结构的C#模型类
首先得定义和你的JSON响应对应的类,这样序列化工具才能把JSON字符串转成你能直接操作的C#对象:
// 匹配单个公司的字段结构 public class Company { public Guid guid { get; set; } public string name { get; set; } public int rating { get; set; } public DateTime rating_date { get; set; } } // 匹配整个JSON响应的根结构(因为你的JSON外层是"companies"数组) public class CompanyResponse { public List<Company> companies { get; set; } }
2. 反序列化JSON响应字符串
把你从REST API拿到的JSON字符串转成上面定义的CompanyResponse对象,这里给两种常用的序列化方案:
用.NET自带的System.Text.Json(推荐,无需额外安装包)
// 假设jsonResponse是你从REST API获取到的完整JSON字符串 var serializeOptions = new JsonSerializerOptions { PropertyNameCaseInsensitive = true // 避免JSON字段和C#属性大小写不匹配的问题 }; CompanyResponse companyResponse = JsonSerializer.Deserialize<CompanyResponse>(jsonResponse, serializeOptions); List<Company> companyList = companyResponse.companies;
用Newtonsoft.Json(如果你习惯用这个库)
先安装NuGet包Newtonsoft.Json,再执行反序列化:
CompanyResponse companyResponse = JsonConvert.DeserializeObject<CompanyResponse>(jsonResponse); List<Company> companyList = companyResponse.companies;
3. 批量上传到SharePoint列表
现在你已经拿到了List<Company>对象,只需要循环遍历每个公司,结合你已有的上传代码即可。注意750+条数据不要每条单独调用ExecuteQuery,这样性能会很差,建议每50-100条批量提交一次:
using (ClientContext context = new ClientContext("http://exampleSharepoint/List")) { // 这里记得补充SharePoint身份验证逻辑,比如账号密码/应用权限令牌等 List companiesList = context.Web.Lists.GetByTitle("Companies"); int batchSize = 50; // 每50条提交一次,可根据你的环境调整 int currentBatchCount = 0; foreach (var company in companyList) { ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation(); ListItem newItem = companiesList.AddItem(itemCreateInfo); // 注意:这里的字段名要和SharePoint列表的内部名称对应! newItem["Title"] = company.name; // 假设Title字段存公司名称 newItem["guid"] = company.guid.ToString(); // 如果SharePoint的guid字段是文本类型,需转成字符串 newItem["Rating"] = company.rating; newItem["Rating_x0020_Date"] = company.rating_date; // 字段名含空格时,SharePoint内部会替换为_x0020_ newItem.Update(); currentBatchCount++; // 达到批量大小就提交一次请求 if (currentBatchCount >= batchSize) { context.ExecuteQuery(); currentBatchCount = 0; } } // 提交最后一批不足batchSize的数据 if (currentBatchCount > 0) { context.ExecuteQuery(); } }
几个关键注意点
- SharePoint字段名:如果列表字段名有空格(比如"Rating Date"),SharePoint内部会把空格替换成
_x0020_,代码里要写对应的内部名称,可以通过列表设置查看字段的内部名称。 - 身份验证:别忘了根据你的SharePoint环境(比如本地部署/Online)配置身份验证,比如用
NetworkCredential或者Azure AD应用权限。 - 异常处理:建议加try-catch块捕获上传异常,避免一条数据失败导致全部中断,还可以记录失败的公司信息方便后续重试。
- 性能优化:如果数据量更大,还可以考虑用SharePoint的Batch API进一步提升效率,不过上面的批量提交已经足够应对750+条的量级了。
内容的提问来源于stack exchange,提问作者Jherb
相关产品推荐
相关产品推荐

