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

C#如何将API返回的字符串数据存入HashMap或Dictionary中?

实现方案

首先明确:C# 没有名为HashMap的内置类型,功能对等的键值对集合为Dictionary<TKey, TValue>,属于System.Collections.Generic命名空间。
绝大多数汇率API返回的字符串为JSON格式,你需要先将JSON反序列化后提取汇率数据存入Dictionary,具体操作步骤如下:

步骤1:确定API返回结构

首先调用一次接口拿到txt的实际内容,以下是市面主流汇率API的通用返回结构示例:

{
  "base_code": "USD",
  "time_last_update_unix": 1716249600,
  "conversion_rates": {
    "CNY": 7.2341,
    "EUR": 0.9205,
    "GBP": 0.7887,
    "JPY": 155.32,
    "HKD": 7.8012
  }
}

步骤2:定义对应实体类

根据你拿到的实际返回结构定义C#类,以上面示例的JSON结构为例,实体类定义如下:

using System.Collections.Generic;

// 根结构实体
public class RateApiResponse
{
    // 属性名要和JSON返回的键名完全对应,或者加序列化特性指定映射
    public string base_code { get; set; }
    public long time_last_update_unix { get; set; }
    // 汇率字段直接声明为Dictionary类型,序列化工具会自动映射
    public Dictionary<string, decimal> conversion_rates { get; set; }
}

步骤3:反序列化JSON获取Dictionary

你原有代码用的WebClient已被官方标记为过时,这里同时提供兼容原有写法和推荐的HttpClient写法两种实现:

兼容原WebClient的实现(.NET Framework/.NET Core均支持)

需要引入对应序列化库的命名空间:

  • .NET Core 3.0+ / .NET 5+ 推荐用内置的System.Text.Json,引入using System.Text.Json;
  • .NET Framework 可以用Newtonsoft.Json(需先通过Nuget安装Newtonsoft.Json包),引入using Newtonsoft.Json;
    修改后的CurrencyRate类代码:
using System.Net;
using System.Collections.Generic;
using System.Text.Json; // 用Newtonsoft的话替换为 using Newtonsoft.Json;

namespace RateLib
{
    public class CurrencyRate
    {
        public Dictionary<string, decimal> GetRate()
        {
            string url = "你的实际汇率API请求地址";
            WebClient myClient = new WebClient();
            string txt = myClient.DownloadString(url);
            
            // 反序列化得到返回对象
            RateApiResponse response = JsonSerializer.Deserialize<RateApiResponse>(txt);
            // 用Newtonsoft的话替换为 JsonConvert.DeserializeObject<RateApiResponse>(txt);
            
            // conversion_rates本身就是Dictionary类型,直接返回即可
            return response.conversion_rates;
        }
    }
}

推荐的HttpClient实现(性能更高、无过时警告)

using System.Net.Http;
using System.Collections.Generic;
using System.Text.Json;
using System.Threading.Tasks;

namespace RateLib
{
    public class CurrencyRate
    {
        // 全局声明HttpClient避免重复实例化
        private static readonly HttpClient _httpClient = new HttpClient();
        
        public async Task<Dictionary<string, decimal>> GetRateAsync()
        {
            string url = "你的实际汇率API请求地址";
            string txt = await _httpClient.GetStringAsync(url);
            RateApiResponse response = JsonSerializer.Deserialize<RateApiResponse>(txt);
            return response.conversion_rates;
        }
    }
}

特殊情况:API返回非JSON格式(如CSV/纯文本分隔)

如果接口返回的是纯文本分隔的汇率数据,例如每行格式为货币代码,汇率,直接手动拆分后存入Dictionary即可:

public Dictionary<string, decimal> ParseTextToDict(string txt)
{
    Dictionary<string, decimal> rateDict = new Dictionary<string, decimal>();
    // 按行拆分文本
    string[] lines = txt.Split(new[] {'\n', '\r'}, System.StringSplitOptions.RemoveEmptyEntries);
    foreach (string line in lines)
    {
        string[] parts = line.Split(',');
        if(parts.Length == 2 && decimal.TryParse(parts[1], out decimal rate))
        {
            rateDict.Add(parts[0].Trim(), rate);
        }
    }
    return rateDict;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 13:57:03