我在这里找到了一些https://docs.microsoft.com/en-us/azure/hdinsight/hdinsight-dotnet-avro-serialization#Scenario2代码,它们可以颠倒我所需要的:
//Define the schema in JSON
const string Schema = @"{
""type"":""record"",
""name"":""Microsoft.Hadoop.Avro.Specifications.SensorData"",
""fields"":
[
{
""name"":""Location"",
""type"":
{
""type"":""record"",
""name"":""Microsoft.Hadoop.Avro.Specifications.Location"",
""fields"":
[
{ ""name"":""Floor"", ""type"":""int"" },
{ ""name"":""Room"", ""type"":""int"" }
]
}
},
{ ""name"":""Value"", ""type"":""bytes"" }
]
}";
//Create a generic serializer based on the schema
var serializer = AvroSerializer.CreateGeneric(Schema);
我想采用我创建的模型:
[DataContract(Name = "Demo", Namespace = "pubsub.demo")]
public class Demo
{
[DataMember(Name = "value")]
public long Value { get; set; }
}
...并将此C#模型序列化为JSON Avro架构字符串。
原因:
我只想维护C#模型并将这些模型自动注册到Confluent的模式注册表。要向架构注册表注册,架构需要采用JSON Avro格式(就像上面的Schema
一样)。
我不希望同时定义JSON和C#模型。如果我必须维护一个,我更愿意有一个C#模型。
我在Microsoft.Hadoop.Avro.AvroSerializer
中找到了要查找的内容。
AvroSerializer.Create<Demo>().WriterSchema.ToString();
// > {"type":"record","name":"pubsub.demo.Demo","fields"[{"name":"value","type":"long"}]}