【问题标题】:Error reading JObject from JsonReader. Current JsonReader item is not an object in C#从 JsonReader 读取 JObject 时出错。当前 JsonReader 项目不是 C# 中的对象
【发布时间】:2019-03-12 15:23:55
【问题描述】:

我编写了一段代码来从货币转换器中获取一个值,如下所示:

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;

我想通过乘以十进制 230 得到值 '69.657026',并返回最终结果。谁能告诉我我做错了什么,如果可能,请纠正它?

【问题讨论】:

    标签: c#-4.0 mvcrazor


    【解决方案1】:

    目前还不清楚您为什么尝试将 69.657026 解析为 JObject - 它不是对象。

    我怀疑您根本不需要这样做 - 只需使用 JObj.USD_INR 作为小数:

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

    一般来说,您来回转换的次数似乎比您需要的要多。这是我认为您正在尝试做的完整示例:

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

    或者,不使用动态类型:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-13
      • 1970-01-01
      • 2022-11-27
      • 2017-04-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多