You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从WebClient调用AlphaVantage汇率API返回的JSON中提取汇率?

嘿,这事儿好办!你已经拿到了API返回的JSON字符串,接下来只需要解析它就能提取汇率啦。我给你两种常用的实现方式,分别适配不同的.NET环境:

方法1:使用Json.NET(Newtonsoft.Json)

这是.NET Framework中最常用的JSON处理库,步骤很简单:

  1. 先通过NuGet安装包:
    Install-Package Newtonsoft.Json
    
  2. 解析JSON提取汇率,你可以用动态类型快速实现,或者创建实体类保证类型安全:

动态类型解析(快速上手)

using Newtonsoft.Json;
using System;
using System.Net;

// 你的原有请求代码
WebClient web = new WebClient();
Uri uri = new Uri(string.Format("https://www.alphavantage.co/query?function=CURRENCY_EXCHANGE_RATE&from_currency={0}&to_currency={1}&apikey=demo", currFrom, currTo));
string response = web.DownloadString(uri);

// 解析JSON获取汇率
dynamic jsonData = JsonConvert.DeserializeObject(response);
string exchangeRateStr = jsonData["Realtime Currency Exchange Rate"]["5. Exchange Rate"];
// 转成数值类型方便计算
decimal exchangeRate = Convert.ToDecimal(exchangeRateStr);

实体类解析(类型安全)

先定义和JSON结构匹配的实体类:

public class CurrencyExchangeResponse
{
    [JsonProperty("Realtime Currency Exchange Rate")]
    public RealtimeExchangeRate RealtimeCurrencyExchangeRate { get; set; }
}

public class RealtimeExchangeRate
{
    [JsonProperty("5. Exchange Rate")]
    public string ExchangeRate { get; set; }
    // 如果你需要其他字段(比如货币名称、刷新时间),可以在这里补充定义
}

然后解析:

var responseObj = JsonConvert.DeserializeObject<CurrencyExchangeResponse>(response);
string exchangeRateStr = responseObj.RealtimeCurrencyExchangeRate.ExchangeRate;
decimal exchangeRate = Convert.ToDecimal(exchangeRateStr);
方法2:使用System.Text.Json(.NET Core/.NET 5+ 内置)

如果你用的是较新的.NET版本,直接用内置的System.Text.Json就行,不用额外安装包:

动态解析

using System;
using System.Net;
using System.Text.Json;

// 原有请求代码
WebClient web = new WebClient();
Uri uri = new Uri(string.Format("https://www.alphavantage.co/query?function=CURRENCY_EXCHANGE_RATE&from_currency={0}&to_currency={1}&apikey=demo", currFrom, currTo));
string response = web.DownloadString(uri);

// 配置序列化选项(忽略大小写,适配JSON键的格式)
var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
dynamic jsonData = JsonSerializer.Deserialize<dynamic>(response, options);
string exchangeRateStr = jsonData["Realtime Currency Exchange Rate"]["5. Exchange Rate"].GetString();
decimal exchangeRate = Convert.ToDecimal(exchangeRateStr);

实体类解析

同样先定义实体类:

public class CurrencyExchangeResponse
{
    [JsonPropertyName("Realtime Currency Exchange Rate")]
    public RealtimeExchangeRate RealtimeCurrencyExchangeRate { get; set; }
}

public class RealtimeExchangeRate
{
    [JsonPropertyName("5. Exchange Rate")]
    public string ExchangeRate { get; set; }
}

然后解析:

var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
var responseObj = JsonSerializer.Deserialize<CurrencyExchangeResponse>(response, options);
string exchangeRateStr = responseObj.RealtimeCurrencyExchangeRate.ExchangeRate;
decimal exchangeRate = Convert.ToDecimal(exchangeRateStr);
额外小贴士:替换WebClient为HttpClient

注意:WebClient已经被标记为过时API,推荐使用更高效、支持异步操作的HttpClient来发送请求,示例代码:

using System;
using System.Net.Http;
using System.Threading.Tasks;

// 异步请求示例
public async Task<decimal> GetExchangeRate(string currFrom, string currTo)
{
    using (HttpClient client = new HttpClient())
    {
        string url = string.Format("https://www.alphavantage.co/query?function=CURRENCY_EXCHANGE_RATE&from_currency={0}&to_currency={1}&apikey=demo", currFrom, currTo);
        string response = await client.GetStringAsync(url);
        
        // 这里可以用上面任意一种JSON解析方式获取汇率
        dynamic jsonData = JsonConvert.DeserializeObject(response);
        return Convert.ToDecimal(jsonData["Realtime Currency Exchange Rate"]["5. Exchange Rate"]);
    }
}

内容的提问来源于stack exchange,提问作者IMRUP

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 03:53:47