从JSON中检索值

时间:2018-01-11 10:23:54

标签: c# json

我正在从JSON中检索值并想要比较它。但我得到的索引超出范围异常:

string email = contactdata.data[0].email[i].value;

代码:

 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类:

  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; }
    }

4 个答案:

答案 0 :(得分:2)

更改行

int length = contactdata.data.Length;

int length = contactdata.data[0].email.Length;

并将for循环中的条件从i <= length更改为i < length

答案 1 :(得分:0)

更改此

for (int i = 0; i <= length; i++)

for (int i = 0; i < length; i++)

index start alwais from 0

答案 2 :(得分:0)

您的迭代变量位于contactdata.data不在电子邮件上,因此您的i变量位于这些索引上。

答案 3 :(得分:0)

正如我在评论中提到的,使用嵌套for循环数据和ALSO通过电子邮件确保您实际上有一封电子邮件可以查看!

索引超出范围错误意味着您尝试访问不存在的数组中的项目。

我没有测试下面的代码,但我在循环中使用了非常明确的变量名来向您展示我想要计算的内容,以及如果我知道它实际上我只能访问数组中的某些内容存在:

//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
     }
  }
}