phpsymfonyserializationdenormalized

How convert string to int with Symfony Serializer


I'm trying to denormalize an array into an object, but when the denormalize method comes across a code field that is a number, it gets an error since it is a string in the array, maybe it's fashionable to fix it

{
  "name": "Exception",
  "message": "The type of the \"code\" attribute for class \"App\\Http\\Response\\Flight\\DriverResponse\" must be one of \"int\" (\"string\" given).",
  "code": 0,
  "type": "Symfony\\Component\\Serializer\\Exception\\NotNormalizableValueException",
  "file": "/app/vendor/symfony/serializer/Normalizer/AbstractObjectNormalizer.php",
  "line": 445,
  "stack-trace": [
    "#0 /app/vendor/symfony/serializer/Normalizer/AbstractObjectNormalizer.php(331): Symfony\\Component\\Serializer\\Normalizer\\AbstractObjectNormalizer->validateAndDenormalize('App\\\\Http\\\\Respon...', 'code', '1', 'array', Array)",
    "#1 /app/vendor/symfony/serializer/Serializer.php(185): Symfony\\Component\\Serializer\\Normalizer\\AbstractObjectNormalizer->denormalize(Array, 'App\\\\Http\\\\Respon...', 'array', Array)",
    "#2 /app/src/Http/Response/Transformer.php(96): Symfony\\Component\\Serializer\\Serializer->denormalize(Array, 'App\\\\Http\\\\Respon...', 'array')",
    "#3 [internal function]: App\\Http\\Response\\Transformer->App\\Http\\Response\\{closure}(Array)",
    "#4 /app/src/Http/Response/Transformer.php(98): array_map(Object(Closure), Array)",
    "#5 /app/src/Http/Controllers/Api/Flight/DriverController.php(124): App\\Http\\Response\\Transformer->transform(Object(yii\\data\\SqlDataProvider), 'drivers', 'App\\\\Http\\\\Respon...')",
    "#6 [internal function]: App\\Http\\Controllers\\Api\\Flight\\DriverController->actionIndex()",
    "#7 /app/vendor/yiisoft/yii2/base/InlineAction.php(57): call_user_func_array(Array, Array)",
    "#8 /app/vendor/yiisoft/yii2/base/Controller.php(157): yii\\base\\InlineAction->runWithParams(Array)",
    "#9 /app/vendor/yiisoft/yii2/base/Module.php(528): yii\\base\\Controller->runAction('index', Array)",
    "#10 /app/vendor/yiisoft/yii2/web/Application.php(103): yii\\base\\Module->runAction('Api/Flight/driv...', Array)",
    "#11 /app/vendor/yiisoft/yii2/base/Application.php(386): yii\\web\\Application->handleRequest(Object(yii\\web\\Request))",
    "#12 /app/web/index.php(14): yii\\base\\Application->run()",
    "#13 {main}"
  ]
}

Solution

  • I fixed it, just need to pass this setting [AbstractObjectNormalizer::DISABLE_TYPE_ENFORCEMENT => true]

    $this->serializer->denormalize(
        $array,
        $class,
       'array',
       [AbstractObjectNormalizer::DISABLE_TYPE_ENFORCEMENT => true]
    );