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

无法解析JSON中的字符串数组?银行API汇率解析问题求助

解决JSON数组反序列化失败问题

你当前的Rates属性定义为string类型,但API返回的exchangeRate是一个对象数组,JSON序列化器无法将数组直接转换为字符串,导致解析失败。解决方法是匹配正确的类型结构:

1. 创建单个汇率项的实体类

对应JSON中exchangeRate数组里的对象结构,注意部分字段是可选的,用可空类型处理:

public class ExchangeRateItem
{
    [JsonPropertyName("baseCurrency")]
    public string BaseCurrency { get; set; }

    [JsonPropertyName("currency")]
    public string Currency { get; set; }

    [JsonPropertyName("saleRateNB")]
    public decimal SaleRateNB { get; set; }

    [JsonPropertyName("purchaseRateNB")]
    public decimal PurchaseRateNB { get; set; }

    // saleRate和purchaseRate并非所有币种都返回,设为可空类型
    [JsonPropertyName("saleRate")]
    public decimal? SaleRate { get; set; }

    [JsonPropertyName("purchaseRate")]
    public decimal? PurchaseRate { get; set; }
}

2. 修改ExchangeRate类的Rates属性类型

把原来的string类型改成集合类型(比如List<ExchangeRateItem>),同时可以根据需求添加其他需要解析的字段:

public class ExchangeRate
{
    [JsonPropertyName("date")]
    public string Date { get; set; }

    [JsonPropertyName("bank")]
    public string Bank { get; set; }

    [JsonPropertyName("baseCurrency")]
    public int BaseCurrencyCode { get; set; }

    [JsonPropertyName("baseCurrencyLit")]
    public string BaseCurrencyLiteral { get; set; }

    [JsonPropertyName("exchangeRate")]
    public List<ExchangeRateItem> Rates { get; set; }
}

3. 原解析代码无需改动

修改完实体类后,原来的ProcessExchangeRate方法可以直接使用,序列化器会自动将exchangeRate数组映射到Rates属性中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 12:27:35