【发布时间】:2016-11-29 11:42:54
【问题描述】:
我正在努力处理一个 json 对象。
我使用以下代码创建了对象 (RO),并且运行良好。
string reply = @"" + client.UploadString(url, "POST", LS_json);
RootObject RO = new RootObject();
RO = JsonConvert.DeserializeObject<RootObject>(reply);
RO 现在包含我通过 json 搜索收到的所有数据。
现在,当迭代对象时,foreach 迭代的对象多于 (RO) 包含的内容:
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++;
}
问题是,当 cnt_V == 4 并且“指向”最后一个条目属性 [cnt_V] 时,LS_ande 会按预期填充 (=="KEY_VALUES")。
但随后 foreach 再次迭代(cnt_V == 5),这里没有问题,但是当它分配给 LS_ande 时,它会转储(当然是因为没有包含 cnt_V == 5 数据的条目)。
我不明白怎么了。请对我温柔一点,并随时询问更多信息。 提前致谢。
【问题讨论】:
-
遍历 RO.hits.hits[0]._source.Vrvirksomhed.deltagerRelation[cnt_I].organisationer[cnt_III].medlemsData[cnt_IV].attributter[cnt_V].type 这样的长路径会导致如果中间对象之一为空,则会出错。你必须测试没有一个中间对象是空的。
-
@jdweng 已经尝试过了。它没有成功: if (RO.hits.hits[0]._source.Biz.Rel[cnt_I].org[cnt_III].mem[cnt_IV].attributes[cnt_V].values[0].value ! = null) { LS_ande = "" + Convert.ToString(RO.hits.hits[0]._source.Biz.Rel[cnt_I].org[cnt_III].mem[cnt_IV].attributes[cnt_V].values[0] 。价值); }
-
RootObject RO = new RootObject();是一种浪费,如果您在下一行中指定与RO不同的内容。改为考虑var RO = JsonConvert.DeserializeObject<RootObject>(reply); -
如果“转储”是指
NullReferenceException,那么这是What is a NullReferenceException, and how do I fix it?的副本 -
@crashmstr 不是。取而代之的是:System.ArgumentOutOfRangeException