获取嵌套 json 元素 returns 出错
Getting Nested json element returns an error
我正在尝试制作一个与 randomuser.me API 交互的应用程序
但这总是 returns 有点错误,这次我使用我在 Whosebug 中找到的代码来解析 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
它returns这样的错误:
System.ArgumentException: Accessed JArray values with invalid key value: >"name". Array position index expected.
at Newtonsoft.Json.Linq.JArray.get_Item(Object key)
当路径中有数组索引时,尝试像您正在做的那样在点上拆分 JSON 路径是行不通的。幸运的是,您不必推出自己的查询方法;内置的 SelectToken()
方法完全符合您的要求:
using (WebClient wc = new WebClient())
{
var json = wc.DownloadString("https://randomuser.me/api/");
JToken token = JToken.Parse(json);
string firstName = (string)token.SelectToken("results[0].name.first");
string lastName = (string)token.SelectToken("results[0].name.last");
string city = (string)token.SelectToken("results[0].location.city");
string username = (string)token.SelectToken("results[0].login.username");
...
}
Fiddle: https://dotnetfiddle.net/3kh0b0
我正在尝试制作一个与 randomuser.me API 交互的应用程序 但这总是 returns 有点错误,这次我使用我在 Whosebug 中找到的代码来解析 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
它returns这样的错误:
System.ArgumentException: Accessed JArray values with invalid key value: >"name". Array position index expected.
at Newtonsoft.Json.Linq.JArray.get_Item(Object key)
当路径中有数组索引时,尝试像您正在做的那样在点上拆分 JSON 路径是行不通的。幸运的是,您不必推出自己的查询方法;内置的 SelectToken()
方法完全符合您的要求:
using (WebClient wc = new WebClient())
{
var json = wc.DownloadString("https://randomuser.me/api/");
JToken token = JToken.Parse(json);
string firstName = (string)token.SelectToken("results[0].name.first");
string lastName = (string)token.SelectToken("results[0].name.last");
string city = (string)token.SelectToken("results[0].location.city");
string username = (string)token.SelectToken("results[0].login.username");
...
}
Fiddle: https://dotnetfiddle.net/3kh0b0