Avro 架构:无法使字段可选

Avro schema: Cannot make fields optionable

我在我的 avro 模式中定义了一个字段,如下所示。

                {
                  "name": "currency",
                  "type": ["null","string"],
                  "default": null
                },

我收到一些数据 json 因为它不包含字段货币并且它总是抛出这个错误。

Expected field name not found: currency

我使用以下代码将其转换为通用对象。

       DecoderFactory decoderFactory = new DecoderFactory();
        Decoder decoder = decoderFactory.jsonDecoder(schema, eventDto.toString());
        DatumReader<GenericData.Record> reader =
                new GenericDatumReader<>(schema);
        GenericRecord genericRecord = reader.read(null, decoder);

大多数 Whosebug 和 github 答案表明我在上面所做的应该使字段成为可选的并且应该可以正常工作。但这似乎对我不起作用。有什么办法可以解决吗

这是一个很常见的误解。 Java JSON 解码器在未找到字段时不使用默认值。这是因为 JSON 编码器在创建 JSON 时会包含该字段,因此解码器希望该字段存在。

如果您想支持它以您期望的方式使用默认值,您可以在 their tracker here 上找到类似的问题并添加评论。