如何修复Pydantic使用第三方注解类型时的「默认值不可JSON序列化」警告?
问题分析与解决
问题背景
通过Annotated为第三方不可修改的Quantity类添加Pydantic注解,实现了模型的JSON序列化/反序列化,但生成JSON Schema时,默认值Quantity(value=0.0, unit='m')被判定为不可序列化,导致默认值被排除出Schema,抛出non-serializable-default警告。
原因
Pydantic的JSON Schema生成逻辑与模型实例序列化逻辑是独立的:
- 模型序列化时,会通过
QuantityAnnotations的wrap验证器将Quantity对象转换为可序列化的字典结构; - 但生成Schema时,会直接检查原始的
Quantity默认值对象,找不到对应的序列化规则,因此判定其不可序列化。
简便解决方法
方法1:为Annotated类型添加序列化器
使用PlainSerializer明确指定Quantity对象的序列化逻辑,让Schema生成器能正确解析默认值:
from typing import Annotated, Any from pydantic import BaseModel, model_validator, PlainSerializer from pydantic.functional_validators import ModelWrapValidatorHandler from typing_extensions import Self # 第三方不可修改类 class Quantity: def __init__(self, value: float, unit: str): self.value = value self.unit = unit class QuantityAnnotations(BaseModel): value: float unit: str @model_validator(mode="wrap") def _validate(value: Any, handler: ModelWrapValidatorHandler[Self]) -> Quantity: if isinstance(value, Quantity): return value validated = handler(value) if isinstance(validated, Quantity): return validated return Quantity(**dict(validated)) # 新增PlainSerializer定义序列化逻辑 QuantityType = Annotated[ Quantity, QuantityAnnotations, PlainSerializer(lambda q: {"value": q.value, "unit": q.unit}, return_type=dict) ] class OurModel(BaseModel): quantity: QuantityType = Quantity(value=0.0, unit='m')
执行OurModel.model_json_schema()时,默认值会被正确序列化为{"value":0.0,"unit":"m"}并加入Schema,无警告。
方法2:通过json_schema_extra手动补充默认值
若不想修改Annotated类型定义,可在模型中手动指定Schema的默认值:
class OurModel(BaseModel): quantity: QuantityType = Quantity(value=0.0, unit='m') model_config = { "json_schema_extra": { "properties": { "quantity": {"default": {"value": 0.0, "unit": "m"}} } } }
这种方式无需改动类型注解,适合快速修复,但需注意默认值变动时要手动同步。
内容的提问来源于stack exchange,提问作者bjmc
相关产品推荐
相关产品推荐

