Symfony Serializer报错:无法将int转为float属性
解决Symfony Serializer反序列化int转float报错问题
方案一:启用宽松类型转换
直接修改ObjectNormalizer的实例化配置,开启enableTypeLoosening参数,让Serializer自动兼容兼容类型转换(比如int转float):
$this->serializer = new Serializer([ new DateTimeNormalizer(), // 开启enableTypeLoosening参数 new ObjectNormalizer(null, null, null, new ReflectionExtractor(), null, true), new ArrayDenormalizer() ], [ new JsonEncoder( new JsonEncode(), new JsonDecode(), ) ]);
这个参数会允许系统自动处理诸如int转float这类兼容类型转换,不会再抛出NotNormalizableValueException异常。
方案二:自定义类型转换器(精细控制)
如果需要只针对特定类型(比如仅int转float)做转换,而保持其他类型的严格检查,可以自定义一个类型转换器:
1. 创建转换器类
use Symfony\Component\Serializer\Converter\PropertyTypeConverterInterface; class IntToFloatConverter implements PropertyTypeConverterInterface { public function convert(mixed $value, string $type, array $context = []): mixed { // 仅当目标类型是float且原始值是int时,执行转换 if ($type === 'float' && is_int($value)) { return (float)$value; } return $value; } public function supports(mixed $value, string $type, array $context = []): bool { return $type === 'float' && is_int($value); } }
2. 配置到Serializer中
$this->serializer = new Serializer([ new DateTimeNormalizer(), // 传入自定义转换器 new ObjectNormalizer( null, null, null, new ReflectionExtractor(), new IntToFloatConverter() ), new ArrayDenormalizer() ], [ new JsonEncoder( new JsonEncode(), new JsonDecode(), ) ]);
这样就只会处理int到float的转换,其他类型不匹配的情况依然会抛出异常,保持类型检查的严格性。
内容的提问来源于stack exchange,提问作者Mitsukk
相关产品推荐
相关产品推荐

