Can someone help me with this? I'm trying to serialize an object to json using the Symfony Serializer, it does convert object to json but it doesnt convert an array of objects from camelCase to snake_case.
Im currently using the default Serializer with Symfony 3.3
Below is my code.
framework:
serializer:
enabled: true
name_converter: 'serializer.name_converter.camel_case_to_snake_case'
services:
get_set_method_normalizer:
class:Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer
public: true
tags: [serializer.normalizer]
Persons.php
class Person{
private $firstName;
private $lastName;
private $email;
//setters and getters
}
PersonController.php
class PersonController extends Controller {
/**
* @Route("api/person")
* @Method("POST")
*/
public function person(){
$person = new Person();
$person->setFirstName("test");
$person->setLastName("test");
$person->setEmail("[email protected]");
$person1 = new Person();
$person1->setFirstName("test 1");
$person1->setLastName("test 1");
$person1->setEmail("[email protected]");
$arr = array($person, $person1);
$serializer = $this->get("serializer");
return new Response($serializer->serialize($arr,"json"));
}
}
Below is the current output.
[
{
"firstName":"test",
"lastName":"test"
"email":"[email protected]"
},
{
"firstName":"test 1",
"lastName":"test 1"
"email":"[email protected]"
}
]
Expected output would be:
[
{
"first_name":"test",
"last_name":"test",
"email":"[email protected]"
},
{
"first_name":"test 1",
"last_name":"test 1",
"email":"[email protected]"
}
]
For symfony 4 this worked for me:
Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer:
public: true
arguments: ['@serializer.mapping.class_metadata_factory', '@serializer.name_converter.camel_case_to_snake_case']
tags: [serializer.normalizer]
Put that code inside your app/config/services.yaml, inside the "services" section.
try explicitly pass arguments for your service:
get_set_method_normalizer:
class:Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer
public: true
arguments: ['@serializer.mapping.class_metadata_factory', '@serializer.name_converter.camel_case_to_snake_case']
tags: [serializer.normalizer]
It is easier to add an alias for camel_case_to_snake_case
services:
...
Symfony\Component\Serializer\NameConverter\NameConverterInterface: '@serializer.name_converter.camel_case_to_snake_case'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With