在C#中实现JSON RPC对接Pyth.Network读取数据的开发咨询
C# 对接 Pyth Network JSON RPC 实现指引
依赖说明
不需要引入第三方JSON RPC封装库,仅使用微软官方原生库即可实现,完全避免依赖匹配问题:
- .NET Core 3.0 / .NET 5 及以上版本:
System.Net.Http、System.Text.Json均为框架自带,无需额外安装NuGet包 - .NET Framework 版本:可直接在NuGet包管理器搜索安装对应版本的官方
System.Net.Http、System.Text.Json包即可
核心实现代码
1. 定义请求、返回值通用结构体
using System.Text.Json.Serialization; // JSON RPC 通用请求结构体 public class JsonRpcRequest { [JsonPropertyName("jsonrpc")] public string JsonRpcVersion { get; set; } = "2.0"; [JsonPropertyName("method")] public string Method { get; set; } [JsonPropertyName("params")] public object[] Params { get; set; } [JsonPropertyName("id")] public int RequestId { get; set; } = 1; } // JSON RPC 通用返回结构体 public class JsonRpcResponse<T> { [JsonPropertyName("jsonrpc")] public string JsonRpcVersion { get; set; } [JsonPropertyName("id")] public int RequestId { get; set; } [JsonPropertyName("result")] public T Result { get; set; } [JsonPropertyName("error")] public RpcError Error { get; set; } } public class RpcError { [JsonPropertyName("code")] public int Code { get; set; } [JsonPropertyName("message")] public string Message { get; set; } } // Pyth 喂价返回结构体示例,可根据需要调用的接口扩展 public class PythPriceFeed { [JsonPropertyName("id")] public string FeedId { get; set; } [JsonPropertyName("price")] public PythPriceInfo Price { get; set; } } public class PythPriceInfo { [JsonPropertyName("price")] public string RawPrice { get; set; } [JsonPropertyName("conf")] public string ConfidenceInterval { get; set; } [JsonPropertyName("expo")] public int Exponent { get; set; } }
2. 封装JSON RPC请求方法
using System.Net.Http; using System.Text; using System.Text.Json; public class PythJsonRpcClient { // 全局单例复用HttpClient,避免套接字资源耗尽 private static readonly HttpClient _httpClient = new HttpClient { // 替换为你使用的Pyth RPC节点地址 BaseAddress = new Uri("你的Pyth RPC节点地址") }; private static readonly JsonSerializerOptions _jsonOptions = new JsonSerializerOptions { PropertyNameCaseInsensitive = true }; public async Task<T> InvokeAsync<T>(string method, params object[] parameters) { var requestBody = new JsonRpcRequest { Method = method, Params = parameters }; var content = new StringContent( JsonSerializer.Serialize(requestBody), Encoding.UTF8, "application/json" ); var httpResponse = await _httpClient.PostAsync(string.Empty, content); httpResponse.EnsureSuccessStatusCode(); var responseStr = await httpResponse.Content.ReadAsStringAsync(); var rpcResponse = JsonSerializer.Deserialize<JsonRpcResponse<T>>(responseStr, _jsonOptions); if (rpcResponse.Error != null) { throw new Exception($"RPC请求错误:{rpcResponse.Error.Code} - {rpcResponse.Error.Message}"); } return rpcResponse.Result; } }
3. 调用示例
// 初始化客户端 var pythClient = new PythJsonRpcClient(); // 示例:调用get_price_feed接口获取BTC/USD喂价,参数替换为对应币种的喂价ID var btcFeed = await pythClient.InvokeAsync<PythPriceFeed>("get_price_feed", "e62df6c8b4a85fe1a67db44dc12de5db330f7ac66b72dc658afedf0f4a415b43"); // 计算得到实际喂价 decimal actualPrice = decimal.Parse(btcFeed.Price.RawPrice) * (decimal)Math.Pow(10, btcFeed.Price.Exponent); Console.WriteLine($"BTC/USD 喂价:{actualPrice:F2} USD,置信区间:{btcFeed.Price.ConfidenceInterval}");
常见问题排查
- 依赖报错:确认安装的NuGet包版本和你的项目.NET框架版本匹配,优先使用框架自带的原生库,无需引入其他第三方RPC封装包
- 请求失败:检查RPC节点地址是否可正常访问,请求方法名、参数顺序与类型是否符合接口要求
- 反序列化失败:先打印接口返回的原始JSON字符串,对照调整实体类的字段名与
JsonPropertyName配置
内容的提问来源于stack exchange,提问作者CopyPasteGhost
相关产品推荐
相关产品推荐

