Avro:反序列化json-具有可选字段的架构 [英] Avro: deserialize json - schema with optional fields
问题描述
关于该主题的堆栈溢出问题很多,但没有一个可以帮助您.
There are a lot of questions and answers on stackoverflow on the subject, but no one that helps.
我有一个带有可选值的模式:
I have a schema with optional value:
{
"type" : "record",
"name" : "UserSessionEvent",
"namespace" : "events",
"fields" : [ {
"name" : "username",
"type" : "string"
}, {
"name" : "errorData",
"type" : [ "null", "string" ],
"default" : null
}]
}
我正在尝试反序列化json而没有此字段:
And I'm trying deserialize json w/o this field:
{
"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
The only way that works is json
{
"username" : "2271AE67-34DE-4B43-8839-07216C5D10E1",
"errorData" : null
}
是否有一种方法可以在不使用此字段的情况下反序列化json?
Is there a way to deserialize json w/o this field?
另一个问题:当此字段在此处时,我应该写
Another question: when this field is here, I should write
{
"username" : "2271AE67-34DE-4B43-8839-07216C5D10E1",
"errorData" : { "string":"070226AC-9B91-47CE-85FE-15AA17972298"}
}
是否可以反序列化普通" json:
Is there a way to deserialize a "normal" json:
{
"username" : "2271AE67-34DE-4B43-8839-07216C5D10E1",
"errorData" : "070226AC-9B91-47CE-85FE-15AA17972298"
}
?
推荐答案
案例1在Java中工作正常.
case 1 is working fine in java .
{
"username" : "2271AE67-34DE-4B43-8839-07216C5D10E1",
"errorData" : { "string":"070226AC-9B91-47CE-85FE-15AA17972298"}
}
对于情况2,
您的架构被定义为并集.您可以按如下所示更新架构,以反序列化json.
for case 2 Your schema is defined for union. You can update you schema as below to deserialize 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
}]
}
这篇关于Avro:反序列化json-具有可选字段的架构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!