Avro:反序列化 json - 带有可选字段的模式

Avro: deserialize json - schema with optional fields

关于这一主题的 Whosebug 上有很多问题和答案,但没有人能提供帮助。

我有一个带有可选值的模式:

{
 "type" : "record",
 "name" : "UserSessionEvent",
 "namespace" : "events",
 "fields" : [ {
   "name" : "username",
   "type" : "string"
 }, {
   "name" : "errorData",
   "type" : [ "null", "string" ],
   "default" : null
 }]
}

我正在尝试反序列化 json w/o 这个字段:

{
 "username" : "2271AE67-34DE-4B43-8839-07216C5D10E1",
 "errorData" : { "string":"070226AC-9B91-47CE-85FE-15AA17972298"}
}

使用代码:

val reader = new GenericDatumReader[GenericRecord](schema)
val decoder = DecoderFactory.get().jsonDecoder(schema, json)
reader.read(null, decoder)

我得到了:org.apache.avro.AvroTypeException: Expected field name not found: errorData

唯一可行的方法是 json

{
 "username" : "2271AE67-34DE-4B43-8839-07216C5D10E1",
 "errorData" : null

}

有没有办法反序列化jsonw/o这个字段?

另外一个问题:当这个字段在这里的时候,我应该写

{
 "username" : "2271AE67-34DE-4B43-8839-07216C5D10E1",
 "errorData" : { "string":"070226AC-9B91-47CE-85FE-15AA17972298"}

}

有没有办法反序列化一个 "normal" json:

{
 "username" : "2271AE67-34DE-4B43-8839-07216C5D10E1",
 "errorData" : "070226AC-9B91-47CE-85FE-15AA17972298"
}

?

案例 1 在 java 中运行良好。

{
"username" : "2271AE67-34DE-4B43-8839-07216C5D10E1",
"errorData" : { "string":"070226AC-9B91-47CE-85FE-15AA17972298"}
}

对于案例 2 您的架构是为联合定义的。您可以按以下方式更新架构以反序列化 json.

 {
   "username" : "2271AE67-34DE-4B43-8839-07216C5D10E1",
   "errorData" : "070226AC-9B91-47CE-85FE-15AA17972298"
 }

{
  "type" : "record",
  "name" : "UserSessionEvent",
  "namespace" : "events",
  "fields" : [ {
                "name" : "username",
                "type" : "string"
             }, {
                "name" : "errorData",
                "type" :  "string" ,
                "default" : null
               }]
}