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

能否从C# record生成Avro schema?及获取方法咨询

从C# Record生成Avro Schema的方法

当然可以通过Avro.Reflect命名空间从标注后的C# record生成Avro schema,具体实现步骤如下:

1. 为Record添加Avro属性标注

使用AvroFieldAttribute标记record的属性,指定Avro字段的名称、类型等信息,示例代码:

using Avro.Reflect;

public record UserRecord
{
    [AvroField("user_id")]
    public int UserId { get; init; }

    [AvroField("user_name")]
    public string UserName { get; init; }

    [AvroField("is_active")]
    public bool IsActive { get; init; }
}

2. 通过Reflector生成Schema

利用Avro.Reflect.Reflector类的GetSchema方法,传入目标record的类型,即可直接生成对应的Avro schema。示例代码:

using Avro;
using Avro.Reflect;

var userSchema = Reflector.GetSchema(typeof(UserRecord));
// 输出Schema的JSON格式字符串
Console.WriteLine(userSchema.ToString());

执行后会输出类似如下的Avro schema内容:

{
  "type": "record",
  "name": "UserRecord",
  "fields": [
    {"name": "user_id", "type": "int"},
    {"name": "user_name", "type": "string"},
    {"name": "is_active", "type": "boolean"}
  ]
}

额外扩展说明

  • 若需要自定义record对应的Avro名称或命名空间,可以给record类添加AvroRecordAttribute:
[AvroRecord(Name = "User", Namespace = "com.example.avro")]
public record UserRecord { /* 属性定义 */ }
  • 对于嵌套record、枚举等复杂类型,只要确保嵌套类型也正确添加了Avro标注,Reflector就能自动识别并生成对应的嵌套Schema结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 18:30:54