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

将JSON反序列化为Pydantic模型时遇空Route对象报错问题

问题原因

你定义的List[Optional[Route]]表示列表元素可以是Route对象或None,但JSON里的空字典{}和None不是一回事。Pydantic会把空字典当成要解析成Route的输入,但Route里有多个必填字段(比如vehicleStartTime),所以触发了必填字段缺失的错误。

解决方案

提供两种可行的解决方式,按需选择:

方法1:给模型加字段验证器(推荐)

在OptimizationResponse模型中添加一个前置验证器,把routes列表里的空字典自动转为None,让Optional[Route]能正常接收:

from pydantic import BaseModel, field_validator
from typing import List, Optional

# 保留你原有的Route、SkippedShipment、AggregatedGlobalMetrics等模型定义

class OptimizationResponse(BaseModel):
    routes: List[Optional[Route]]
    skippedShipments: Optional[List[SkippedShipment]] = []
    metrics: AggregatedGlobalMetrics

    @field_validator('routes', mode='before')
    def convert_empty_dict_to_none(cls, value):
        # 遍历routes列表,将空字典替换为None
        return [None if item == {} else item for item in value]

验证器的mode='before'参数表示在Pydantic解析字段之前先执行处理逻辑,确保空字典被转换成合法的None值。

方法2:解析前手动处理JSON数据

如果不想修改模型,可以在解析前先处理JSON内容,把routes里的空字典替换为None:

# 原有的JSON读取代码不变
json_response = MessageToJson(fleet_routing_response._pb)
async with aiofiles.open(self.config.get('api', 'response_file'), 'w') as response_file:
    await response_file.write(json_response)

# 解析前处理JSON数据
json_data = json.loads(json_response)
if 'routes' in json_data:
    json_data['routes'] = [None if item == {} else item for item in json_data['routes']]

# 再执行反序列化
optimization_response = parse_obj_as(OptimizationResponse, json_data)
return optimization_response

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 01:52:39