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

Symfony反序列化报错:amount应为int却传入string,如何正确处理?

问题解决方法

先排查两个核心问题,逐步解决:

1. 修正ManyToMany字段的JSON格式错误

你的Product实体中$price是ManyToMany关联,对应的数据结构应为集合(数组),但你传入的JSON是单个对象,这会导致序列化器无法正确解析,间接引发类型错误。调整JSON格式为:

{
    "name": "asd",
    "price": [
        {"amount": 3}
    ]
}

同时确保Product实体的构造函数中初始化集合:

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;

class Product
{
    // ...其他字段

    #[ORM\ManyToMany(targetEntity: Price::class)]
    private Collection $price;

    public function __construct()
    {
        $this->price = new ArrayCollection();
    }

    // ...添加对应getter/setter方法
}

2. 解决数值类型被解析为字符串的问题

方法一:开启序列化器的类型转换功能

在Symfony序列化配置文件config/packages/serializer.yaml中添加配置,开启自动类型转换:

framework:
    serializer:
        enable_annotations: true
        normalizers:
            object_normalizer:
                enabled: true
                enable_type_conversion: true

该配置会让序列化器自动将可转换的字符串数值转为对应类型,同时保留类型检查逻辑。

方法二:为字段添加序列化类型注解

在Price实体的$amount字段上显式声明序列化类型:

use Symfony\Component\Serializer\Annotation\Type;

class Price
{
    #[ORM\Column(type: 'integer')]
    #[Type('int')]
    private int $amount;

    // ...添加对应getter/setter方法
}

此注解会强制序列化器将该字段解析为整数类型。

方法三:确保请求头正确设置

确认请求的Content-Type头为application/json,若请求头不正确,Symfony可能会错误地将JSON数值解析为字符串。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 05:07:44