1

I'm calling Google Maps and use System.JSON to parse the object. I grab my object using:

double placeLat = json["results"][0]["geometry"]["location"]["lat"];

Then I want to check wheater the third objects exists and if yes perform some actions, but apparently the following fails. I know that Google Maps returns 2 objects in this case and I want to check for the third one to avoid performing actions on null and passing them further.. The following works fine when Google Maps returns 3 objects so I believe my condition is wrong.

if (json["results"][2] != null) {

        }

I get this error:

Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index

Any ideas of how to properly build the if statement in case using System.JSON?

Mac_W
  • 2,927
  • 6
  • 17
  • 30

3 Answers3

6
if(jsonobject.Count>0)
 {
 }     
Abhishek Kanrar
  • 418
  • 4
  • 6
2

If the results array only has two entries in it, then you can't access json["results"][2] because index 2 is outside the bounds of the array.

Before you access index 2, check json["results"].Count to make sure index 2 exists. You might need to cast it to JsonArray before you access the Count.

Saeed
  • 287
  • 2
  • 7
0
var response = await httpClient.PostAsync(uri, content);
                    var instituteDetails = await response.Content.ReadAsStringAsync();
                    **if (response.IsSuccessStatusCode && instituteDetails.Length>2)**
                    {
                        createModel = JsonConvert.DeserializeObject<IList<PaymentResponseDetailsModel>>(instituteDetails);
                        **if(createModel.Count()>0)**
                        {
                            return View(createModel);
                        }
                        else
                        {
                            return RedirectToAction("RegistrationInfo");
                        }
                       });                           
                    }
R2Psoft
  • 19
  • 2
  • if (response.IsSuccessStatusCode && instituteDetails.Length>2) and if(createModel.Count()>0) worked fine if you getting empty jsonstring and model . – R2Psoft May 07 '20 at 13:25