2017-06-05 121 views
0

我想使用symfony/serializer将我的实体序列化为json。 我想要得到的东西像用symfony序列化程序错误序列化

{ 
    "id" : "string", 
    "name" : "name here", 
    "admin": "admin_id" 
    } 

但我总是最后一棵完整的树 - 生成的JSON包含所有相关实体与它们之间的关系。我相信它必须是symfony/serializer的小任务,显然是做错了什么,但是什么?

CarbonNormalizer只是返回nesbot /碳对象的字符串表示形式。

这里是我的控制器:

$data=$this->em->getRepository('Cpa:Cpa')->findAll(); 
    $encoder = new JsonEncoder(); 
    $normalizer = new GetSetMethodNormalizer();//object -same 
    $dateTimeNormalizer = new CarbonNormalizer(); 
    $normalizer->setCircularReferenceHandler(function ($object) { 
     return $object->getId(); 
    }); 
    $this->serializer = new Serializer([$dateTimeNormalizer, $normalizer], [$encoder]); 

    $data = $this->serializer->serialize($data, 'json', ['groups' => ['show'], 'enable_max_depth' => true]); 
    return new JsonResponse($data, $code, [], true); 

而且我的实体:

<?php 

namespace Domain\Cpa\Models; 


use Domain\Offer\Models\CpaOffer; 
use Domain\User\Models\User; 
use Ramsey\Uuid\Uuid; 

class Cpa 
{ 
/** @var string */ 
private $id; 

/** @var string */ 
private $name; 

/** @var User */ 
private $admin; 

/** @var CpaOffer[] */ 
private $offers; 

/** 
* Cpa constructor. 
* @param string $name 
* @param User $admin 
*/ 
public function __construct($name, User $admin) 
{ 
    $this->id = Uuid::uuid4()->toString(); 
    $this->name = $name; 
    $this->admin = $admin; 
    $this->offers = []; 
} 

/** 
* @return string 
*/ 
public function getId(): string 
{ 
    return $this->id; 
} 

/** 
* @return string 
*/ 
public function getName(): string 
{ 
    return $this->name; 
} 

/** 
* @return User 
*/ 
public function getAdmin(): User 
{ 
    return $this->admin; 
} 

/** 
* @return CpaOffer[] 
*/ 
public function getOffers()//: array 
{ 
    return $this->offers; 
} 

}

serialization.yml

Domain\Cpa\Models\Cpa: 
attributes: 
    id: 
    groups: ['show'] 
    name: 
    groups: ['show'] 
    admin: 
    groups: ['show'] 

回答

0

要使用组,则需要初始化ClassMetadataFactory太:

// Don't forget to add the new use statements 
// ... 
$normalizer = new GetSetMethodNormalizer(
    new ClassMetadataFactory(
    new YamlFileLoader('/the/path/to/yourfile.yaml') 
) 
); 
// ... 

还必须解决您的YAML文件的缩进:

'Domain\Cpa\Models\Cpa': 
    attributes: 
    id: 
     groups: ['show'] 
    name: 
     groups: ['show'] 
    admin: 
     groups: ['show'] 
+0

谢谢,凯文。有没有办法将配置的序列化器注入到我的服务/控制器中? '/the/path/to/yourfile.yaml' - 是否是serialization.yml的路径? – svgrafov