【问题标题】:Getting Nested json element returns an error获取嵌套的 json 元素返回错误
【发布时间】: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(对象键)

【问题讨论】:

标签: c# .net json json.net webclient


【解决方案1】:

当路径中有数组索引时,尝试像您正在做的那样在点上拆分 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");
    ...
}

小提琴:https://dotnetfiddle.net/3kh0b0

【讨论】:

  • 谢谢您,这与预期的一样正常工作。
  • 很高兴我能帮上忙。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-29
  • 2020-07-11
  • 1970-01-01
相关资源
最近更新 更多