我有以下代码行
$apps = $appRepositry->findBy(['user' => $user]);
然后我使用以下内容通过JSON返回结果
$json_data[] = array(
"state" => "success",
"user_apps" => $apps,
"total_registerd_apps" => count($apps),
);
我遇到的问题是计数正确,但是“ user_apps”数组返回空白。
{
state = success;
"total_registerd_apps" = 1;
"user_apps" = (
{
}
);
}
我认为这是因为FindBy返回对象,但我不确定。有人可以解释如何将结果转换为可以通过JSON发送的数组吗?
谢谢
答案 0 :(得分:0)
您需要对组使用序列化程序。
有关序列化的信息: http://symfony.com/doc/current/components/serializer.html
有关序列化组的信息: https://symfony.com/blog/new-in-symfony-2-7-serialization-groups
public function listAction(ParamFetcherInterface $paramFetcher, Request $request)
{
//...your code...//
$yourObjectifiedResult = $appRepositry->findBy(['user' => $user]);
$yourNormalizedResult = $this->normalizeWithCircularHandler(
$yourObjectifiedResult,
['groups']);
//Serializer will convert your result from Object to Json Array automatically. To get a specific set of data, you can use groups.
}
public function normalizeWithCircularHandler($data, $displayGroups, $normalizerCallbacks = false)
{
$encoder = new JsonEncoder();
$classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));
$normalizer = new ObjectNormalizer($classMetadataFactory);
$normalizer->setCircularReferenceHandler(function ($object) {
return $object->getId();
});
if(false != $normalizerCallbacks && is_array($normalizerCallbacks)) {
$normalizer->setCallbacks($normalizerCallbacks);
}
$serializer = new Serializer([$normalizer], [$encoder]);
return $serializer->normalize($data , null, ['groups' => $displayGroups]);
}
答案 1 :(得分:-1)
您需要使用序列化程序将数据序列化为JSON: https://symfony.com/doc/current/serializer.html