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

C#如何从WebSocket服务端返回的JSON响应中提取指定字段(如price)

解决方案

要提取JSON响应中的指定字段,你需要对WebSocket返回的JSON字符串做反序列化解析,以下是两种可直接落地的实现方案:

方案1:使用.NET自带的System.Text.Json(无需额外安装依赖)

.NET Core 3.0+ 及 .NET 5+ 自带System.Text.Json序列化库,不需要额外安装NuGet包即可使用。

强类型解析(推荐,稳定性更高)

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

using System.Text.Json.Serialization;

public class TickerResponse
{
    [JsonPropertyName("type")]
    public string Type { get; set; }
    
    [JsonPropertyName("product_id")]
    public string ProductId { get; set; }
    
    [JsonPropertyName("price")]
    public string Price { get; set; }
    
    // 其他需要提取的字段可以按照以上格式补充
}

修改你代码中MessageReceived的订阅逻辑:

using System.Text.Json;

client.MessageReceived.Subscribe(msg => 
{
    // 若你使用的WebSocket客户端返回的msg是字符串类型,直接赋值即可
    // 部分封装的WebSocket客户端需取msg.Text获取纯JSON内容,可根据实际情况调整
    string jsonContent = msg.ToString();
    
    try
    {
        var response = JsonSerializer.Deserialize<TickerResponse>(jsonContent);
        // 仅处理ticker类型的消息,避免其他类型消息解析报错
        if (response != null && response.Type == "ticker" && response.ProductId == "ETH-USD")
        {
            // 提取price字段,如需数值计算可转decimal:decimal priceVal = decimal.Parse(response.Price)
            Console.WriteLine($"ETH-USD最新价格:{response.Price}");
        }
    }
    catch (JsonException)
    {
        // 非预期格式的消息可直接忽略或打日志排查
    }
});

动态解析(无需定义实体类,适合临时使用场景)

如果不想提前定义实体类,可以用JsonDocument动态解析字段:

using System.Text.Json;

client.MessageReceived.Subscribe(msg => 
{
    string jsonContent = msg.ToString();
    try
    {
        using var jsonDoc = JsonDocument.Parse(jsonContent);
        var root = jsonDoc.RootElement;
        if (root.GetProperty("type").GetString() == "ticker" && root.GetProperty("product_id").GetString() == "ETH-USD")
        {
            string price = root.GetProperty("price").GetString();
            Console.WriteLine($"ETH-USD最新价格:{price}");
        }
    }
    catch
    {
        // 异常处理逻辑
    }
});

方案2:使用Newtonsoft.Json(Json.NET,兼容老版本.NET框架)

如果你项目用的是.NET Framework或者习惯用Newtonsoft.Json,先安装Newtonsoft.Json NuGet包,再修改代码:

using Newtonsoft.Json.Linq;

client.MessageReceived.Subscribe(msg => 
{
    string jsonContent = msg.ToString();
    try
    {
        dynamic response = JObject.Parse(jsonContent);
        if (response.type == "ticker" && response.product_id == "ETH-USD")
        {
            string price = response.price;
            Console.WriteLine($"ETH-USD最新价格:{price}");
        }
    }
    catch
    {
        // 异常处理逻辑
    }
});

注意事项

  • 涉及货币类数值计算时,推荐将price字段转为decimal类型,避免double类型的精度丢失问题
  • 接口返回的消息包含heartbeat、level1等多种类型,必须先判断type字段为ticker再取price,否则会触发字段不存在的运行时错误
  • 若你用的是原生System.Net.WebSockets,接收的是字节数组,需要先通过Encoding.UTF8.GetString()将字节数组转为UTF8字符串再解析

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 12:15:01