【问题标题】:Convert API String to JSON Object using NewtonSoft.Json使用 NewtonSoft.Json 将 API 字符串转换为 JSON 对象
【发布时间】:2018-12-31 18:53:38
【问题描述】:

我已经阅读了许多询问类似问题的主题,但无法将它们全部联系在一起。

我有一个 API 在这里输入一个字符串:https://apiv2.bitcoinaverage.com/constants/exchangerates/local

我想让这个字符串可用且可访问。例如获取美元对加元的汇率。

我在我的代码中使用 RestSharp 和 Newtonsoft JSON。

using Newtonsoft.Json;
using RestSharp;

首先我使用http://json2csharp.com/ 创建一个匹配字符串的类(类?)。编辑:我现在已经解决了这个问题,并且必须按照修改后的代码正确嵌套类;

class Exrates
{
    public Rates rates { get; set; }
    public string time { get; set; }

    public class Rates
    {
        public MXN Mxn { get; set; }
        public ILS Ils { get; set; }
        public EUR Eur { get; set; }
        public BRL Brl { get; set; }
        public PLN Pln { get; set; }
        public MYR Myr { get; set; }
        public SEK Sek { get; set; }
        public AUD Aud { get; set; }
        public IDR Idr { get; set; }
        public TRY Try { get; set; }
        public RUB Rub { get; set; }
        public JPY Jpy { get; set; }
        public CAD Cad { get; set; }
        public USD Usd { get; set; }
        public GBP Gbp { get; set; }
        public NZD Nzd { get; set; }
        public CZK Czk { get; set; }
        public SGD Sgd { get; set; }

    public class MXN
        {
            public string name { get; set; }
            public string rate { get; set; }
        }

        public class ILS
        {
            public string name { get; set; }
            public string rate { get; set; }
        }

        public class EUR
        {
            public string name { get; set; }
            public string rate { get; set; }
        }

        public class BRL
        {
            public string name { get; set; }
            public string rate { get; set; }
        }

        public class PLN
        {
            public string name { get; set; }
            public string rate { get; set; }
        }

        public class MYR
        {
            public string name { get; set; }
            public string rate { get; set; }
        }

        public class SEK
        {
            public string name { get; set; }
            public string rate { get; set; }
        }

        public class AUD
        {
            public string name { get; set; }
            public string rate { get; set; }
        }

        public class IDR
        {
            public string name { get; set; }
            public string rate { get; set; }
        }

        public class TRY
        {
            public string name { get; set; }
            public string rate { get; set; }
        }

        public class RUB
        {
            public string name { get; set; }
            public string rate { get; set; }
        }

        public class JPY
        {
            public string name { get; set; }
            public string rate { get; set; }
        }

        public class CAD
        {
            public string name { get; set; }
            public string rate { get; set; }
        }

        public class USD
        {
            public string name { get; set; }
            public string rate { get; set; }
        }

        public class GBP
        {
            public string name { get; set; }
            public string rate { get; set; }
        }

        public class NZD
        {
            public string name { get; set; }
            public string rate { get; set; }
        }

        public class CZK
        {
            public string name { get; set; }
            public string rate { get; set; }
        }

        public class SGD
        {
            public string name { get; set; }
            public string rate { get; set; }
        }
    }
}

然后我调用 API 并将响应存储在字符串中;

    var btcAvgClient = new RestClient();
    btcAvgClient.BaseUrl = new Uri("https://apiv2.bitcoinaverage.com/constants/exchangerates/local");

    IRestResponse response;
    var request = new RestRequest();

    response = btcAvgClient.Execute(request);
    string btcAvg = response.Content;

我相信还有 1 或 2 个步骤,但我无法完全弄清楚。我现在如何将此字符串转换为可用的东西?

感谢任何帮助!

【问题讨论】:

标签: c# json restsharp


【解决方案1】:

首先,修改您的数据模型,如下所示:

public class Rate
{
    public string name { get; set; }
    public decimal rate { get; set; }
}

public class RootObject
{
    public Dictionary<string, Rate> rates { get; set; }
    public string time { get; set; }
}

接下来介绍如下扩展方法:

public static partial class RateExtensions
{
    public static bool TryGetConversion(this Dictionary<string, Rate> rates, string from, string to, out decimal rate)
    {
        Rate fromRate;
        Rate toRate;

        if (rates == null || !rates.TryGetValue(from, out fromRate))
        {
            rate = 0;
            return false;
        }

        if (!rates.TryGetValue(to, out toRate))
        {
            rate = 0;
            return false;
        }

        rate = toRate.rate / fromRate.rate;
        return true;
    }
}

现在,您可以执行一个类型化的请求,如下所示。输入的请求会自动将响应反序列化为您想要的数据模型:

var btcAvgClient = new RestClient("https://apiv2.bitcoinaverage.com/");
var request = new RestRequest("constants/exchangerates/local");

// Execute the request and get the typed response
var response = btcAvgClient.Execute<RootObject>(request);

// Get the root object from the response.
RootObject data = response.Data;

然后计算从美元到加元的转换如下:

// Compute the converson from (e.g.) USD to CAD
var fromName = "USD";
var toName = "CAD";

decimal rate;
if (data.rates.TryGetConversion(fromName, toName, out rate))
{
    Console.WriteLine("Conversion from {0} to {1} = {2}", fromName, toName, rate);
}
else
{
    Console.WriteLine("Cannot get conversion from {0} to {1}.", fromName, toName);
}

在我的电脑上这个输出

美元兑换加元 = 1.36245

Google search 确认的当前似乎是正确的数字:

1 美元等于 1.36 加元

注意事项:

  • 由于此 API 将来可能会返回不同的货币,但每种货币的数据相同,因此我将 rates 定义为 Dictionary&lt;string, Rate&gt; rates。字典将捕获所有返回的货币汇率。

    您的代码需要知道预期的货币名称,但我相信这些是标准的。

  • 由于我们在这里进行货币转换,我将rate 定义为decimal 而不是string。序列化程序会自动将"rate" 的字符串值反序列化为十进制。

  • 为确保您的请求成功,请参阅How to idiomatically handle HTTP error codes when using RestSharp?

    或者,您可以查看response.ErrorException,如Recommended Usage 文档页面所示。​​

  • 如果您需要发出async 请求,请参阅How should I implement ExecuteAsync with RestSharp on Windows Phone 7?

  • RestSharp 有一个built-in JSON serializer,但如果你愿意,你可以使用 Json.NET。只需获取response.Content 字符串并通过以下方式反序列化:

    // Execute the request and get the untyped (string) response
    var response = btcAvgClient.Execute(request);
    
    // Get the root object from the response.
    RootObject data = Newtonsoft.Json.JsonConvert.DeserializeObject<RootObject>(response.Content);
    

【讨论】:

  • 感谢您的帮助!我是初学者,在理解您的代码时遇到问题,但进展顺利。我最终解决了上述问题,但会在某个时候回到您的代码以改进我自己的实现。再次感谢您的帮助。
【解决方案2】:

应该是太根对象。

var beers = JsonConvert.DeserializeObject<RootObject>(response.Content);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-27
    • 2020-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-23
    • 2012-06-14
    相关资源
    最近更新 更多