0

I'm trying to a make an application that interacts with the randomuser.me API but this always returns some kinda of error, this time i'm using a code that i've found in stackoverflow to parse the json content. So here is my code rightnow:

   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;
            }


        }

I don't really know what's the exact problem but it's returning a System.NullReferenceException

EDIT

If i don't insert the index in the second parameter of the GetJsonPropretyValue group method, and insert it this way results.name.first It returns such an error:

System.ArgumentException: Accessed JArray values with invalid key value: >"name". Array position index expected.

at Newtonsoft.Json.Linq.JArray.get_Item(Object key)

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300
PHPdevpro
  • 18
  • 6

1 Answers1

0

Trying to split the JSON path on dots like you are doing isn't going to work when you have an array index in the path. Fortunately, you don't have to roll your own query method; the built-in SelectToken() method does exactly what you want:

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

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300