# Avro反序列化失败：联合字段期望特定分支但收到null

- **ID:** `data/avro-record-schema-union-mismatch`
- **领域:** data
- **类别:** type_error
- **验证级别:** ai_generated
- **修复率:** 85%

## 根因

Avro模式定义了一个联合字段（例如，["null", "string"]），但由于模式演变或数据损坏，数据包含null值而模式期望非null分支，或相反。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| Apache Avro 1.11.1 | active | — | — |
| Confluent Avro Serializer 7.4 | active | — | — |
| Python avro 1.11.0 | active | — | — |

## 解决方案

1. ```
   更新Avro模式，将null作为联合的第一个分支：将'["string"]'改为'["null", "string"]'并将默认值设为null。
   ```
2. ```
   使用自定义反序列化器优雅地处理null值，将其映射为默认字符串：if val is None: val = 'default'。
   ```

## 无效尝试

- **Adding a default value of null to the union field in the schema** — The default value applies during schema evolution but does not fix existing data that has mismatched branches. (70% 失败率)
- **Changing the entire field type to a single type (e.g., string) to avoid unions** — This breaks compatibility with existing data and requires re-encoding all messages. (90% 失败率)
