Reputation: 51
I am retrieving values from JSON and want to compare that. but I am getting Index Out of Range Exception on:
string email = contactdata.data[0].email[i].value;
Code:
int length = contactdata.data.Length;
for (int i = 0; i <= length; i++)
{
string email = contactdata.data[0].email[i].value;
if (contactemail == email)
{
counter++;
flag = 1;
break;
}
}
JSON Class:
public class Rootobject
{
public bool success { get; set; }
public Datum[] data { get; set; }
public Additional_Data additional_data { get; set; }
}
public class Additional_Data
{
public Pagination pagination { get; set; }
}
public class Pagination
{
public int start { get; set; }
public int limit { get; set; }
public bool more_items_in_collection { get; set; }
}
public class Datum
{
public int id { get; set; }
public Email[] email { get; set; }
}
public class Email
{
public string label { get; set; }
public string value { get; set; }
public bool primary { get; set; }
}
Upvotes: 0
Views: 73
Reputation: 710
As I mentioned in a comment, using a nested for loop over data and ALSO over email will ensure you actually have an email you can look at!
The index out of range error means that you're trying to access an item in an array that doesn't exist.
I did not test the following code, but I used really explicit variable names in the loop to show you what I'm trying to count, and how I can only access something in an array if I know that it actually exists:
//first get the length of data
var dataLength = contactdata.data.Length;
//now loop through it
for (var dataCounter = 0; dataCounter < dataLength; dataCounter++){
//next get the length of email - is there even an email available?
var emailLength = contactdata.data[dataCounter].email.Length;
for (var emailCounter = 0; emailCounter < emailLength; emailCounter ++){
//now you can access the email and work with it.
if (contactemail == contactdata.data[dataCounter].email[emailCounter]){
// here do your code
}
}
}
Upvotes: 0
Reputation: 105
Your iteration variable is on the contactdata.data
not on email, thus your i
variable is on these indexes.
Upvotes: 0
Reputation: 226
Change this
for (int i = 0; i <= length; i++)
with
for (int i = 0; i < length; i++)
index start alwais from 0
Upvotes: 0
Reputation: 16355
change the line
int length = contactdata.data.Length;
to
int length = contactdata.data[0].email.Length;
and change the condition in the for loop from i <= length
to i < length
.
Upvotes: 2