我在Symfony4上创建了一个REST API,所以我想使用Symfony4的默认序列化器来序列化我的实体。
但我的实体有不寻常的属性名称,使序列化器给我不好的结果。
我试图实施NameConverterInterface
并尝试CamelCaseToSnakeCaseNameConverter
但没有取得好成绩......
我的应用程序上的每个实体都有这种属性,因此@annotation的解决方案无法帮助我
class Product implements EntityInterface
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer", name="PROD_PKEY")
*/
private $PROD_PKEY;
/**
* @ORM\Column(type="string", length=50)
*/
private $PROD_Name;
/**
* @ORM\Column(type="string", length=50)
*/
private $PROD_Code;
以及我如何使用序列化器:
$product = new Product();
$product->setPRODName("Name");
$product->setPRODCode("Code");
$json = $this->serializer->serialize($product, 'json');
$ json的内容是:
{
"pRODName": "Name",
"pRODCode": "Code",
}
但我期待这样的事情:
{
"PROD_Name": "Name",
"PROD_Code": "Code",
}
只是等于我的实体中的属性名称,我不明白为什么第一个字母得到小写,我的下划线出来...
谢谢你的帮助 !
在Symfony中,您可以实现自定义NameConverter来转换json表示中的字段名称。
这些方面的东西应该可以解决问题:
<?php namespace App\Service;
use Symfony\Component\Serializer\NameConverter\AdvancedNameConverterInterface;
class YourCustomNameConverter implements AdvancedNameConverterInterface
{
public function normalize($propertyName, string $class = null, string $format = null, array $context = [])
{
preg_match('/^([a-z]?[A-Z]+)([A-Z]{1}[_a-zA-Z]+)$/', $propertyName, $matches);
if (strstr($propertyName, 'PKEY')) {
return ucfirst(substr_replace($propertyName, '_', -4, 0));
} elseif (count($matches)) {
array_shift($matches);
$matches[0] = ucfirst($matches[0]);
return implode('_', $matches);
} else {
return $propertyName;
}
}
public function denormalize($propertyName, string $class = null, string $format = null, array $context = [])
{
return $propertyName;
}
}
我想你可能需要创建一个自定义序列化程序,我经常使用jmsserializer
bundle并且没有任何问题
How to use JMSSerializer with symfony 4.2
https://symfony.com/doc/current/serializer/custom_normalizer.html