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

使用Avro JsonDecoder解析可空字段时抛出AvroTypeException异常

问题原因
  • Avro 内置的 JsonDecoder 默认严格遵循 Avro 官方 JSON 编码规范,对联合类型字段有特殊格式要求,无法直接解析普通 JSON 结构。
  • 你定义的 field2 类型为 ["null", "string"] 联合类型,默认规则下要求字段值必须显式指定联合类型分支:比如字符串值要写成 {"string": "value2"},null 值要写成 {"null": null},哪怕是可选字段不传递也会被解码器判定为格式异常,抛出你遇到的 Expected start-union. Got END_OBJECT 错误。
解决方案

方案1(推荐:无需修改输入JSON)

Avro 1.9 及以上版本新增了兼容普通 JSON 格式的配置项,开启 allowNonDefaultUnionEncoding 即可:

JsonDecoder jsonDecoder = DecoderFactory.get()
        .configure()
        // 核心配置:开启非标准联合类型编码支持,兼容普通JSON结构
        .allowNonDefaultUnionEncoding(true)
        .jsonDecoder(schema, body);
DatumReader<Object> reader = new GenericDatumReader<>(schema);
Object result = reader.read(null, jsonDecoder);

开启后两种示例 body 都可以正常解析,可选字段不传时会自动填充默认的 null 值。

方案2(不推荐:需要修改输入JSON格式)

如果不能修改解码器配置,需要将输入的 JSON 调整为符合 Avro 官方 JSON 编码规范的格式:

  • 携带 field2 时的格式:
{
    "field1":"value1",
    "field2": {"string": "value2"}
}
  • 不携带 field2 时需要显式传递 null:
{
    "field1":"value1",
    "field2": {"null": null}
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 01:45:03