C#如何提取API返回JSON对象中的项目名称并加载至数组
解决方案
你可以通过以下两种方式快速提取所有项目的name属性数组:
方案1:使用预定义实体类反序列化(推荐)
你已经定义好了匹配的实体类,直接通过Newtonsoft.Json反序列化响应内容即可:
static void Main(string[] args) { var client = new RestClient("https://devops.americannational.com/tfs/defaultcollection/_apis/projects?$top=300&api-version=5.0") { Authenticator = new RestSharp.Authenticators.NtlmAuthenticator() }; client.Timeout = -1; var request = new RestRequest(Method.GET); IRestResponse response = client.Execute(request); // 先校验响应是否成功 if (!response.IsSuccessful) { Console.WriteLine($"请求失败,状态码:{response.StatusCode},错误信息:{response.ErrorMessage}"); return; } var jsonString = response.Content; // 反序列化为预定义的Rootobject对象 Rootobject result = JsonConvert.DeserializeObject<Rootobject>(jsonString); // 提取所有name转为数组 string[] projectNames = result.value.Select(v => v.name).ToArray(); // 后续遍历使用projectNames即可 foreach (var name in projectNames) { Console.WriteLine(name); } }
方案2:直接通过JObject提取(无需依赖实体类)
如果你不想用实体类反序列化,也可以直接基于你已解析的JObject对象操作:
static void Main(string[] args) { var client = new RestClient("https://devops.americannational.com/tfs/defaultcollection/_apis/projects?$top=300&api-version=5.0") { Authenticator = new RestSharp.Authenticators.NtlmAuthenticator() }; client.Timeout = -1; var request = new RestRequest(Method.GET); IRestResponse response = client.Execute(request); if (!response.IsSuccessful) { Console.WriteLine($"请求失败,状态码:{response.StatusCode},错误信息:{response.ErrorMessage}"); return; } var jsonString = response.Content; var jo = JObject.Parse(jsonString); // 直接从value节点提取所有name属性 string[] projectNames = jo["value"].Select(j => j["name"].ToString()).ToArray(); }
注意事项
- 你的Value类中定义的
description字段在API返回示例中不存在,反序列化时该字段会自动赋值为null,不会影响其他属性解析 - Newtonsoft.Json默认支持ISO标准的DateTime格式,
lastUpdateTime字段可以正常解析 - 生产环境使用时建议增加空值判断,避免接口返回结构异常时抛出空引用异常
内容的提问来源于stack exchange,提问作者Sherpa11
相关产品推荐
相关产品推荐

