我的 Avro 架构是 -
{架构:{“类型”:“记录”,“名称”:“标题”,“命名空间”:“EMployee.schema”,“字段”:[{“名称”:“changeTypes”,“默认”:null ,"type":["null",{"type":"array","items":["null","string"]}]},{"name":"correlationId","default":null ,"type":["null","string"]},{"name":"entityId","default":null,"type":["null","string"]},{"name" :"entityType","default":null,"type":["null","string"]},{"name":"eventTimestamp","default":null,"type":["null", "string"]},{"name":"eventType","default":null,"type":["null","string"]},{"name":"originalEventType","default":null ,"type":["null","string"]},{"name":"originalSourceSystem","default":null,"type":["null","string"]},{"name" :"sourceId","default":null,"type":["null","string"]},{"name":"sourceSystem","default":null,"type":["null", “字符串”]}]},
内容:{changeTypes:System.Collections.Generic.List`1 [System.String],correlationId:c4f6c7fb001546c5ad436376a502ff31,entityId:1,entityType:Employee,eventTimestamp:4/14/2024 4:19:45 PM,eventType:createEmployee ,originalEventType:创建,originalSourceSystem:Workday,sourceId:2,sourceSystem:Workday,}}
如果我们检查模式内容,
changeType
的值是System.Collections.Generic.List
1[System.String]. I am using the method below to assign values to the
GenericRecord`对象。但是,当我将其发布到 Redpanda 主题时,它会抛出错误。
在 ["null",{"type":"array","items":["null","string"]} 中找不到 System.Collections.Generic.List`1[System.String] 的匹配项] 在字段标题中的字段changeTypes中。
我的代码是-
static object ConvertToAvroCompatibleType(Avro.Schema schema, object value)
{
if (schema is Avro.UnionSchema unionSchema)
{
var actualSchema = unionSchema.Schemas.FirstOrDefault(s => s.Tag != Avro.Schema.Type.Null);
if (actualSchema == null)
{
return null;
}
return ConvertToAvroCompatibleType(actualSchema, value);
}
else
{
switch (schema.Tag)
{
case Avro.Schema.Type.String:
return value?.ToString();
case Avro.Schema.Type.Int:
return value is int ? (int)value : 0;
case Avro.Schema.Type.Array:
var arraySchema = (ArraySchema)schema;
var avroArray = new List<string>();
if (value is IEnumerable enumerable)
{
foreach (var item in enumerable)
{
avroArray.Add(item?.ToString());
}
return avroArray;
}
else
{
return null;
}
default:
return null;
}
}
}
任何人都可以帮助我如何将数组传递到 GenericRecord 中吗?或者您能否就这种情况下可能出现的问题提出建议?
static object ConvertToAvroCompatibleType(Avro.Schema schema, object value)
{
if (schema is Avro.UnionSchema unionSchema)
{
var actualSchema = unionSchema.Schemas.FirstOrDefault(s => s.Tag != Avro.Schema.Type.Null);
if (actualSchema == null)
{
return null;
}
return ConvertToAvroCompatibleType(actualSchema, value);
}
else
{
switch (schema.Tag)
{
case Avro.Schema.Type.String:
return value?.ToString();
case Avro.Schema.Type.Int:
return value is int ? (int)value : 0;
case Avro.Schema.Type.Array:
var arraySchema = (ArraySchema)schema;
var avroArray = new List<string>();
if (value is IEnumerable enumerable)
{
foreach (var item in enumerable)
{
avroArray.Add(item?.ToString());
}
return avroArray;
}
else
{
return null;
}
default:
return null;
}
}
}
我解决了这个问题:- 我没有返回“return avroArray”,而是使用“return avroArray.ToArray()”。它正在工作。