WebClient client = new WebClient();
Stream stream = client.OpenRead(" some link ");
StreamReader reader = new StreamReader(stream);
Newtonsoft.Json.Linq.JObject jObject = Newtonsoft.Json.Linq.JObject.Parse(reader.ReadLine());
List<String> list = new List<string>();
//loading list
for (int i = 0; i < ((string)jObject["some_stream"][i]["some_channel"]["some_name"]).Count(); i++)
{
string result = ((string)jObject["some_streams"][i]["some_channel"]["some_name"]);
list.Insert(i, result);
}
stream.Close();
此代码正常运行,但在json数据中我应该返回20多个结果,但我只得到8个。
可能是什么原因?
答案 0 :(得分:1)
你正在计算一个字符串的长度。在某些时候,该字符串的长度等于或小于i(如果您设法迭代8次,则为字符串的第9个值)
这就是这段代码
((string)jObject["some_stream"][i]["some_channel"]["some_name"]).Count()
返回位置i
处字符串的长度,所以如果你设法迭代8次,那么jObject [“some_stream”] [9] [“some_channel”] [“some_name”]的字符串有一个长度当循环结束时为9或更小
从用法看起来jObject["Some_stream"]
返回一个数组,在这种情况下你可以做的是这样的:
var arr = (Treal[])jObject["Some_stream"];
var list = (from obj in arr
select ((string)obj["some_channel"]["some_name"])).ToList();
你需要用实际类型的jObject替换TReal [“Some_stream”]
除此之外:当你打开一个流时,最好在using语句中执行此操作。在您的代码中,在异常情况下不会关闭流 那么代码就是
WebClient client = new WebClient();
using(var stream = client.OpenRead(" some link ")) {
reader = new StreamReader(stream);
var jObject = Newtonsoft.Json.Linq.JObject.Parse(reader.ReadLine());
var arr = (Treal[])jObject["Some_stream"];
var list = (from obj in arr
select ((string)obj["some_channel"]["some_name"])).ToList();
}