Reputation: 114
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.
/**
* @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".
Upvotes: 1
Views: 919
Reputation: 3188
In new versions of Symfony, you can use Symfony\Component\Serializer\Attribute\SerializedName
attribute/annotation for specify name of property.
Example:
<?php
declare(strict_types = 1);
namespace Acme\Resource\Order;
use Symfony\Component\Serializer\Attribute\SerializedName;
use Symfony\Component\Uid\Uuid;
readonly class PayOrderResource implements ResourceInterface
{
public function __construct(
public Uuid $id,
public Money $money,
public OrderStatus $status,
public OrderFlowResource $flow,
public ?DeclinedInfoResource $declinedInfo,
public Tags $tags,
#[SerializedName('_links')]
public ?array $links = null
) {
}
Upvotes: 0
Reputation: 437
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.
You can check answer here to do that: Renaming object keys name in PHP Laravel
Upvotes: 0