Search code examples
c#-4.0mvcrazor

Error reading JObject from JsonReader. Current JsonReader item is not an object in C#


I have written a piece of code to get a value from a currency converter like below:

WebClient n = new WebClient();
var JsonData = n.DownloadString("http://currencyconverterapi.com/api/v6/convert?q=USD_NRI&compact=ultra&apiKey=");   
JsonData = {"USD_INR":69.657026} // Got value result from JsonData
dynamic JObj = JObject.Parse(JsonData);            
dynamic JOresult = JObject.Parse(Convert.ToString(JObj.USD_INR)); //Got Error here (Error reading JObject from JsonReader. Current JsonReader item is not an object: Float. Path '', line 1, position 9.)        
string JOFilter_Val = Convert.ToString(JOresult.val);
decimal Total = 230 * Convert.ToDecimal(JOFilter_Val);
return Total;

I want to get the value '69.657026' from multiplying with the decimal 230, and return the final result. Can anybody tell me what I'm doing wrong and if possible please correct it?


Solution

  • It's not really clear why you're trying to parse 69.657026 as a JObject - it's not an object.

    I suspect you don't need to do that at all - just use JObj.USD_INR as a decimal:

    decimal value = JObj.USD_INR; // Use the dynamic conversion to handle this
    

    In general you seem to be converting back and forth far more than you need to. Here's a complete example of what I think you're trying to do:

    using Newtonsoft.Json.Linq;
    using System;
    
    class Test
    {
        static void Main()
        {
            string json = "{ \"USD_INR\": 69.657026 }";
            dynamic obj = JObject.Parse(json);
            decimal rate = obj.USD_INR;
            decimal total = 230 * rate;
            Console.WriteLine(total); // 16021.115980
        }
    }
    

    Alternatively, without dynamic typing:

    using Newtonsoft.Json.Linq;
    using System;
    
    class Test
    {
        static void Main()
        {
            string json = "{ \"USD_INR\": 69.657026 }";
            JObject obj = JObject.Parse(json);
            decimal rate = (decimal) obj["USD_INR"];
            decimal total = 230 * rate;
            Console.WriteLine(total);
        }
    }