Lars Hansen
Lars Hansen

Reputation: 153

Problems with iteration in json object

Im struggling with a json object.

I create the object (RO) with the following code and that Works fine.

string reply = @"" + client.UploadString(url, "POST", LS_json);
RootObject RO = new RootObject();
RO = JsonConvert.DeserializeObject<RootObject>(reply);

RO now contains all the data I have recieved through the json search.

Now, when iterating through the object the foreach iterate one more than (RO) contains:

cnt_V = 0;
foreach (object obj_attributtertype in RO.hits.hits[0]._source.Biz.Rel[cnt_I].org[cnt_III].mem[cnt_IV].attributter[cnt_V].type)
{
  if (Convert.ToString(RO.hits.hits[0]._source.Biz.Rel[cnt_I].mem[cnt_III].xsData[cnt_IV].attributes[cnt_V].type) == "KEY_VALUES")
  {
    LS_ande = "" + Convert.ToString(RO.hits.hits[0]._source.Biz.Rel[cnt_I].mem[cnt_III].xsData[cnt_IV].attributes[cnt_V].values[0].value);
  }
  cnt_V++; 
}

The thing is that when cnt_V == 4 and "points" to the last entry attributes[cnt_V] then LS_ande is filled as supposed (=="KEY_VALUES").

But then the foreach iterates again (cnt_V == 5), no problem here, but when it is assigned to LS_ande then it dumps (of cource because there is no entry with data for cnt_V == 5).

I dont understand whats wrong. Please be gentle with me and feel free to ask for further information. Thanks in advance.

Upvotes: 1

Views: 69

Answers (1)

crashmstr
crashmstr

Reputation: 28573

While I can't answer this definitively because I don't have the data, this is what I would start with:

//take out the long and lengthy parts to make the rest clearer
//I see there are two things here, intentional?
var something = RO.hits.hits[0]._source.Biz.Rel[cnt_I].org[cnt_III].mem[cnt_IV].attributter;
var somethingElse = RO.hits.hits[0]._source.Biz.Rel[cnt_I].mem[cnt_III].xsData[cnt_IV].attributes;
cnt_V = 0;
//Here, you are iterating over something[cnt_V].type, but also change cnt_V in the body.
//Are you sure this is correct?
foreach (object obj_attributtertype in something[cnt_V].type)
{
    if (Convert.ToString(somethingElse[cnt_V].type) == "KEY_VALUES")
    {
        LS_ande = "" + Convert.ToString(somethingElse[cnt_V].values[0].value);
    }
    cnt_V++; 
}

And looking at it that way, here is my stab in the dark.
Iterate with a for over the Count() of items in something

var something = RO.hits.hits[0]._source.Biz.Rel[cnt_I].org[cnt_III].mem[cnt_IV].attributter;
var somethingElse = RO.hits.hits[0]._source.Biz.Rel[cnt_I].mem[cnt_III].xsData[cnt_IV].attributes;
for (var cnt_V = 0; cnt_V < something.Count(); ++cnt_V)
{
    if (Convert.ToString(somethingElse[cnt_V].type) == "KEY_VALUES")
    {
        LS_ande = "" + Convert.ToString(somethingElse[cnt_V].values[0].value);
    }
    cnt_V++; 
}

Upvotes: 1

Related Questions