简体   繁体   English

使用 objectNormalizer 更改属性名称

[英]change name of property with objectNormalizer

I have the fucntion bellow on my controller but I need to change the name of the fields of the returned Json to a custom name.我的控制器上有以下功能,但我需要将返回的 Json 的字段名称更改为自定义名称。

 /**
 * @Route("/exportar-prefeituras", name="exportar_prefeituras", methods={"POST"})
 */
public function ajaxExportarPrefeituras():Response
{
  $retorno = $this->getDoctrine()->getRepository(Prefeitura::class)->findAll();

  $normalizer = [new ObjectNormalizer()];
  $encoder = [new JsonEncoder()];
  $serializer = new Serializer($normalizer, $encoder);
  
  return new JsonResponse($serializer->normalize($retorno));

}

Is there a way I can do that with some parameters?有没有办法用一些参数来做到这一点? I've seen some things about creating a new nameConverter function, like this but I wanted to know if it can be done on a "simpler way".我已经看到了一些关于创建一个新的 nameConverter 函数的事情,像这样,但我想知道它是否可以以“更简单的方式”完成。

Thanks in advance.提前致谢。

I think the solution on their document is the simpler way you are finding.我认为他们文档上的解决方案是您找到的更简单的方法。 And it can be reuse later else you can add multiple "rename" function.它可以稍后重用,否则您可以添加多个“重命名”功能。

If you want another solution, you can create a function to copy $retorno to another variable and loop through it to rename the keys even set the value.如果您想要其他解决方案,您可以创建一个函数将 $retorno 复制到另一个变量并循环遍历它以重命名键甚至设置值。

You can check answer here to do that: Renaming object keys name in PHP Laravel您可以在此处查看答案: Renaming object keys name in PHP Laravel

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM