有人可以帮我吗? 我尝试使用Symfony Serializer将对象序列化为json,它确实将对象转换为json但它没有将对象数组从camelCase转换为snake_case。
我目前正在使用默认的Serializer with Symfony 3.3
以下是我的代码。
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("test@test.com");
$person1 = new Person();
$person1->setFirstName("test 1");
$person1->setLastName("test 1");
$person1->setEmail("test1@test.com");
$arr = array($person, $person1);
$serializer = $this->get("serializer");
return new Response($serializer->serialize($arr,"json"));
}
}
以下是当前的输出。
[
{
"firstName":"test",
"lastName":"test"
"email":"test@test.com"
},
{
"firstName":"test 1",
"lastName":"test 1"
"email":"test@test.com"
}
]
预期输出为:
[
{
"first_name":"test",
"last_name":"test",
"email":"test@test.com"
},
{
"first_name":"test 1",
"last_name":"test 1",
"email":"test1@test.com"
}
]
答案 0 :(得分:1)
尝试显式传递服务的参数:
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]
答案 1 :(得分:0)
为camel_case_to_snake_case
添加别名更容易
services:
...
Symfony\Component\Serializer\NameConverter\NameConverterInterface: '@serializer.name_converter.camel_case_to_snake_case'
答案 2 :(得分:0)
对于symfony 4,这对我有用:
Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer:
public: true
arguments: ['@serializer.mapping.class_metadata_factory', '@serializer.name_converter.camel_case_to_snake_case']
tags: [serializer.normalizer]
将代码放在“服务”部分的app / config / services.yaml中。