【发布时间】:2017-04-23 23:39:35
【问题描述】:
我正在尝试制作一个与 randomuser.me API 交互的应用程序 但这总是会返回某种错误,这次我使用的是我在 stackoverflow 中找到的代码来解析 json 内容。 所以这是我现在的代码:
public string GetJsonPropertyValue(string json, string query)
{
JToken token = JObject.Parse(json);
foreach (string queryComponent in query.Split('.'))
{
token = token[queryComponent];
}
return token.ToString();
}
string getName()
{
string name = "";
try
{
using (WebClient wc = new WebClient())
{
var json = wc.DownloadString("https://randomuser.me/api/");
name = GetJsonPropertyValue(json, "results[0].name.first");
return name;
}
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
return name;
}
}
我真的不知道确切的问题是什么,但它返回了 System.NullReferenceException
编辑
如果我没有在GetJsonPropretyValue分组方法的第二个参数中插入索引,就这样插入results.name.first
它返回这样一个错误:
System.ArgumentException:使用无效键值访问的 JArray 值:>“名称”。应为数组位置索引。
在 Newtonsoft.Json.Linq.JArray.get_Item(对象键)
【问题讨论】:
-
请参阅编辑@DourHighArch
-
原始 JSON 字符串是什么样的?
标签: c# .net json json.net webclient