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

如何在C#中将AlphaVantage API响应解析为实体类

解决AlphaVantage API JSON数据绑定到.NET Core实体类的问题

问题根源分析

你的代码出现两个属性均为null的原因有三个核心问题:

  1. 序列化属性误用:你使用了[JsonProperty](Newtonsoft.Json特性),但.NET Core 6默认使用System.Text.Json,需改用[JsonPropertyName]特性匹配JSON键名。
  2. 键名不匹配:AlphaVantage返回的时间序列数据键是"Time Series (Daily)",但你的实体类未指定该键名,仅用了TimeSeries属性。
  3. 时间序列结构错误:返回的时间序列是日期为键、每日数据对象为值的字典,而非你定义的Dictionary<string, string> Close结构。

正确的实体类定义

根据API返回的JSON结构,定义如下实体类:

using System.Text.Json.Serialization;

public class AlphaVantageData
{
    [JsonPropertyName("Meta Data")]
    public MetaData MetaData { get; set; }

    [JsonPropertyName("Time Series (Daily)")]
    public Dictionary<string, DailyStockData> DailyTimeSeries { get; set; }
}

public class MetaData
{
    [JsonPropertyName("1. Information")]
    public string Information { get; set; }

    [JsonPropertyName("2. Symbol")]
    public string Symbol { get; set; }

    [JsonPropertyName("3. Last Refreshed")]
    public string LastRefreshed { get; set; }

    [JsonPropertyName("4. Output Size")]
    public string OutputSize { get; set; }

    [JsonPropertyName("5. Time Zone")]
    public string TimeZone { get; set; }
}

public class DailyStockData
{
    [JsonPropertyName("1. open")]
    public string Open { get; set; }

    [JsonPropertyName("2. high")]
    public string High { get; set; }

    [JsonPropertyName("3. low")]
    public string Low { get; set; }

    [JsonPropertyName("4. close")]
    public string Close { get; set; }

    [JsonPropertyName("5. adjusted close")]
    public string AdjustedClose { get; set; }

    [JsonPropertyName("6. volume")]
    public string Volume { get; set; }

    [JsonPropertyName("7. dividend amount")]
    public string DividendAmount { get; set; }

    [JsonPropertyName("8. split coefficient")]
    public string SplitCoefficient { get; set; }
}

修正后的请求与反序列化代码

避免使用.Result阻塞线程,改用异步await写法:

var client = new HttpClient();
var response = await client.GetAsync("https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol=RELIANCE.BSE&outputsize=full&apikey=demo");
response.EnsureSuccessStatusCode(); // 确保请求返回成功状态
var json = await response.Content.ReadAsStringAsync();
var data = JsonSerializer.Deserialize<AlphaVantageData>(json);

关键说明

  • DailyTimeSeries的Dictionary<string, DailyStockData>类型完美匹配API返回的日期键值对结构,每个日期对应一条完整的每日股票数据。
  • 所有字段通过[JsonPropertyName]指定了与JSON完全一致的键名,保证序列化器能正确映射。
  • 若需将收盘价、成交量等数值转为decimal或long,可直接修改DailyStockData的属性类型,System.Text.Json会自动完成合法数值的类型转换。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 23:27:33