Symfony反序列化DirectorDetails类触发NotBlank/NotNull验证错误
解决Symfony中JSON反序列化至DirectorDetails类字段未初始化的问题
问题核心
反序列化后类的所有字段处于未初始化状态,触发Assert\NotBlank验证错误,本质原因是类属性未初始化+JSON字段与类属性名映射不匹配。
具体解决方案
1. 为类属性添加默认初始化值
PHP 8.0+中,声明为非可空类型的属性如果未赋值,会处于uninitialized状态,直接触发非空验证。需要将属性改为可空类型并初始化默认值:
#[ODM\Document(repositoryClass:DirectorDetailsRepository::class)] class DirectorDetails { #[ODM\Id(strategy: "UUID")] private ?string $id = null; #[Assert\NotBlank] #[ODM\Field(type: "string")] private ?string $fullName = null; #[Assert\NotBlank] #[ODM\Field(type: "string")] private ?string $phoneNumber = null; #[Assert\NotBlank] #[Assert\Email(message: "The email '{{ value }}' is not a valid email address.")] #[ODM\Field(type: "string")] private ?string $Email = null; #[Assert\NotBlank] #[ODM\Field(type: "string")] private ?string $ResidentialAddress = null; #[Assert\NotBlank] #[ODM\Field(type: "string")] private ?string $BVN = null; // 原getter/setter代码保持不变 }
2. 用注解明确字段映射关系
类属性存在混合命名规则(如$Email、$fullName),而JSON请求通常使用小驼峰格式,需要通过#[SerializedName]注解指定对应关系:
// 先导入命名空间 use Symfony\Component\Serializer\Annotation\SerializedName; #[ODM\Document(repositoryClass:DirectorDetailsRepository::class)] class DirectorDetails { // ... 其他属性 #[Assert\NotBlank] #[ODM\Field(type: "string")] #[SerializedName('fullName')] private ?string $fullName = null; #[Assert\NotBlank] #[ODM\Field(type: "string")] #[SerializedName('phoneNumber')] private ?string $phoneNumber = null; #[Assert\NotBlank] #[Assert\Email(message: "The email '{{ value }}' is not a valid email address.")] #[ODM\Field(type: "string")] #[SerializedName('email')] private ?string $Email = null; #[Assert\NotBlank] #[ODM\Field(type: "string")] #[SerializedName('residentialAddress')] private ?string $ResidentialAddress = null; #[Assert\NotBlank] #[ODM\Field(type: "string")] #[SerializedName('bvn')] private ?string $BVN = null; // ... 原getter/setter代码保持不变 }
3. 确认JSON请求格式匹配
确保POST请求的JSON字段名与注解指定的一致,示例:
{ "fullName": "John Doe", "phoneNumber": "1234567890", "email": "john@example.com", "residentialAddress": "123 Main St", "bvn": "12345678901" }
4. 可选:配置序列化器自动命名转换
如果不想手动加注解,可在config/packages/serializer.yaml中开启自动驼峰转换:
framework: serializer: name_converter: 'serializer.name_converter.camel_case_to_snake_case' enable_annotations: true
验证效果
修改完成后重新测试接口,反序列化后的字段会被正确赋值,NotBlank验证仅在字段确实为空时触发,对象可正常保存到数据库。
内容的提问来源于stack exchange,提问作者Hassan oladipupo
相关产品推荐
相关产品推荐

