Search code examples
c#json.netjson.netjson-deserialization

Cannot apply indexing with [] to an expression of type object


I'm working on API on the .NET Windows form. I copied the code from the website provided and I found an error say:

Cannot apply indexing with [] to an expression of type 'object'

How to fix this? This is my code:

RestClient restClient = new RestClient("https://api.wassenger.com");
RestRequest restRequest = new RestRequest("/v1/files");
restRequest.Method = Method.Post;
restRequest.AddHeader("Token", "122eb0a65870e715a1de9ad06d11881b841e6db485bd387");
restRequest.AddHeader("Content-Type", "multipart/form-data");
restRequest.AddFile("file", "/path/to/image.jpg");

var response = restClient.Execute(restRequest);
var json = JsonConvert.DeserializeObject(response.Content);
//error at line below (string)json[0]["id]
var fileId = (string)json[0]["id"];

Console.WriteLine("File uploaded successfully with ID: {0}", filed);

The returned response like this:

[
  {
    "id": "606f888ed01a7a65946c0701",
    "format": "native",
    "filename": "sample.jpg",
    "size": 53697,
    "mime": "image/jpeg",
    "ext": "jpeg",
    "kind": "image",
    "sha2":   "305fc37036ffd53aec6d8c4512c0114fd38ac52f85d334e29647a21f0835c801",
    "tags": [],
    "status": "active",
    "mode": "default",
    "createdAt": "2021-05-08T22:49:50.954Z",
    "expiresAt": "2021-09-06T22:49:50.949Z"
  }
]

Solution

  • Assume that your response is a JSON array, you should deserialize it as List<T> which T is the defined class based on your JSON.

    You can use Visual Studio or Json2Csharp to convert the JSON to class.

    public class Root
    {
        [JsonProperty("id")]
        public string Id { get; set; }
    
        [JsonProperty("format")]
        public string Format { get; set; }
    
        [JsonProperty("filename")]
        public string Filename { get; set; }
    
        [JsonProperty("size")]
        public int Size { get; set; }
    
        [JsonProperty("mime")]
        public string Mime { get; set; }
    
        [JsonProperty("ext")]
        public string Ext { get; set; }
    
        [JsonProperty("kind")]
        public string Kind { get; set; }
    
        [JsonProperty("sha2")]
        public string Sha2 { get; set; }
    
        [JsonProperty("tags")]
        public List<object> Tags { get; set; }
    
        [JsonProperty("status")]
        public string Status { get; set; }
    
        [JsonProperty("mode")]
        public string Mode { get; set; }
    
        [JsonProperty("createdAt")]
        public DateTime CreatedAt { get; set; }
    
        [JsonProperty("expiresAt")]
        public DateTime ExpiresAt { get; set; }
    }
    
    string fileId = String.Empty;
    
    List<Root> list = JsonConvert.DeserializeObject<List<Root>>(myJsonResponse);
    
    if (list != null && list.Count > 0)
    {
        fileId = list[0].Id;
    }
    

    Or you can work with JArray.

    using Newtonsoft.Json.Linq;
    
    string fileId = String.Empty;
    
    var jArray = JArray.Parse(response.Content);
    if (jArray != null && jArray.Count > 0)
    {
        fileId = jArray[0]["id"].ToString();
        // Alternative methods    
        // fileId = jArray[0].Value<string>("id"));
        // fileId = jArray[0].SelectToken("id").ToString());
    }