Moyni Moyni - 6 months ago 46
JSON Question

Accessing child value of JSON in C#

public static void apiCall2()
{
WebClient c = new WebClient();
var data = c.DownloadString(baseURL + endPoint + "?access_key=" + accessKey + "&currencies=TWD&source=USD&format=1");
//Console.WriteLine(data);
JObject api = JObject.Parse(data);

string conversion = "";

foreach (var result in api["quotes"])
{
System.Console.WriteLine(result);
conversion = (string)result["USDTWD"];
System.Console.WriteLine(conversion);
}
}


When ever I run this simple JSON API call code I receive an error of


Cannot access child value on Newtonsoft.Json.Linq.JProperty.


The USDTWD (the only section inside of [quotes] is supposed to call a double which returns the exchange rate from USD to TWD, and even trying to call it in as a string does not seem to help.

Answer

When you call foreach (var result in api["quotes"]) you are looping over the child objects of the 'quotes' JObject one of which is the JProperty with property name 'USDTWD'. You then put that JProperty in the result variable. Then here:

conversion = (string)result["USDTWD"]

you are trying to access the USDTWD property of result but result does not have a USDTWD property because it is the USDTWD property. Hence the exception.

If you just need the value of the USDTWD property you can replace your foreach loop with this:

conversion = api["quotes"]["USDTWD"].ToString();