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

如何在C#中读取Azure Event Hubs Schema Registry的JSON事件架构

在C#中读取Azure Event Hubs Schema Registry中的JSON架构并转换为JSON对象

所需依赖

先安装必要的NuGet包:

  • Azure.Messaging.EventHubs.SchemaRegistry:用于操作Schema Registry
  • Newtonsoft.Json(或System.Text.Json):用于将架构内容解析为JSON对象

示例代码

以下是完整的入门示例,包含两种读取架构的方式(通过架构ID、通过架构名称+组):

using Azure.Messaging.EventHubs.SchemaRegistry;
using Newtonsoft.Json.Linq;

// 1. 配置Schema Registry连接信息
string schemaRegistryNamespace = "你的Event Hubs命名空间";
string schemaGroup = "你的架构组名称";
string schemaName = "你的架构名称";
string schemaId = "你的架构ID"; // 已知架构ID时可直接使用
string connectionString = "你的Schema Registry连接字符串(与Event Hubs命名空间连接字符串一致)";

// 2. 初始化SchemaRegistryClient
var client = new SchemaRegistryClient(
    fullyQualifiedNamespace: schemaRegistryNamespace,
    credential: new Azure.Identity.DefaultAzureCredential() // 使用默认Azure凭据,支持本地开发与生产环境
    // 也可以用连接字符串初始化:new SchemaRegistryClient(connectionString)
);

try
{
    // 方式一:通过架构ID读取
    SchemaProperties schemaById = await client.GetSchemaAsync(schemaId);
    JObject schemaJsonById = JObject.Parse(schemaById.SchemaContent);
    Console.WriteLine("通过ID读取的架构JSON:");
    Console.WriteLine(schemaJsonById.ToString());

    // 方式二:通过架构名称+组读取(需确保该组内架构名称唯一)
    SchemaProperties schemaByName = await client.GetSchemaAsync(schemaGroup, schemaName, SchemaFormat.Json);
    JObject schemaJsonByName = JObject.Parse(schemaByName.SchemaContent);
    Console.WriteLine("\n通过名称读取的架构JSON:");
    Console.WriteLine(schemaJsonByName.ToString());
}
catch (Exception ex)
{
    Console.WriteLine($"读取架构时出错:{ex.Message}");
}
finally
{
    await client.DisposeAsync();
}

关键说明

  • 凭据选择:示例中DefaultAzureCredential依赖Azure CLI、环境变量等身份验证方式,适合本地开发和生产环境;如果更倾向于用连接字符串,直接替换客户端初始化逻辑即可。
  • SchemaFormat:因为你的架构是JSON格式,所以指定SchemaFormat.Json参数。
  • JSON解析:示例使用Newtonsoft.Json的JObject,若使用System.Text.Json,可替换为JsonDocument.Parse(schemaContent).RootElement进行解析。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 00:54:56