.NET WinForm调用API报错:Cannot apply indexing with [] to an expression of type 'object'
解决Cannot apply indexing with [] to an expression of type 'object'错误
错误原因
调用JsonConvert.DeserializeObject(response.Content)时未指定具体类型,默认返回object类型,而object不支持[]索引器操作,结合接口返回的JSON数组结构,可通过以下两种方式修复:
方法一:使用强类型模型(推荐,类型安全)
先创建与接口返回结构匹配的实体类:
public class FileResponse { public string id { get; set; } public string format { get; set; } public string filename { get; set; } public int size { get; set; } public string mime { get; set; } public string ext { get; set; } public string kind { get; set; } public string sha2 { get; set; } public List<string> tags { get; set; } public string status { get; set; } public string mode { get; set; } public DateTime createdAt { get; set; } public DateTime expiresAt { get; set; } }
修改反序列化及后续代码:
var response = restClient.Execute(restRequest); // 反序列化为List<FileResponse>类型 var fileResponses = JsonConvert.DeserializeObject<List<FileResponse>>(response.Content); // 直接通过属性访问id var fileId = fileResponses[0].id; // 注意:原代码此处存在变量名笔误,需改为fileId Console.WriteLine("File uploaded successfully with ID: {0}", fileId);
方法二:使用JArray/JObject(无需创建模型,适合快速验证)
先引入Newtonsoft.Json.Linq命名空间,再修改代码:
using Newtonsoft.Json.Linq; // ... 其他请求代码保持不变 var response = restClient.Execute(restRequest); // 解析JSON为JArray类型 var jsonArray = JArray.Parse(response.Content); // 通过索引器获取id var fileId = (string)jsonArray[0]["id"]; // 修正变量名笔误 Console.WriteLine("File uploaded successfully with ID: {0}", fileId);
内容的提问来源于stack exchange,提问作者waleed
相关产品推荐
相关产品推荐

