Moyni Moyni - 1 year ago 259
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");
JObject api = JObject.Parse(data);

string conversion = "";

foreach (var result in api["quotes"])
conversion = (string)result["USDTWD"];

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 Source

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();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download