Symfony 3.4-返回数组JsonResponse

时间:2018-07-31 07:29:40

标签: php json api symfony

我的问题很简单,我想在json中返回一个用于api的数组(使用JsonResponse):

我给你一个我开始做的事的例子:

我的json响应:

{
  "success": "true",
  "message": "Liste du Profil",
  "id": 54,
  "username": "TestTest7",
  "phone": null,
  "email": "noemail@gmail.com",
  "resume": "TestTest7",
  "language": null,
  "friends_added": [
    {
      "id_friend": {}
    }
  ],
  "friends_accepted": [],
  "friends_added_need_to_be_accept": [
    {
      "id_friend": {}
    }
  ],
  "friends_need_to_be_accept": []
}

如您所见,这不是我想要的,因为这些字段是空的:id_friend也作为数据库friends_added_need_to_be_accept中的内容,但是其他两个数据库都为空。

我的控制器:

/**
 *
 * @Rest\Post(
 *     path = "/profile/list",
 *     name = "api_profile_list"
 * )
 * @Rest\View(StatusCode=201, serializerGroups={"user_detail"})
 */
public function ProfileListAction(Request $request)
{
    $em = $this->getDoctrine()->getManager();

    $user = $em->getRepository('AppBundle:User')->findOneBy(array('id' => ($request->get('id_user'))));
    $token = $request->get('token');

    if (!isset($user)) {
        return new JsonResponse([
            'success' => "false",
            'message' => "Utilisateur non renseigné"
        ]);
    }

    if (!isset($token)) {
        return new JsonResponse([
            'success' => "false",
            'message' => "Token non renseigné"
        ]);
    }

    if ($user->getToken() != $token) {
        return new JsonResponse([
            'success' => "false",
            'message' => "Mauvais token",
        ]);
    }
    $profile = $user->getIdProfile();
    $profile = $em->getRepository('AppBundle:Profile')->findOneBy(array('id' => ($profile)));
    $friend_3 = $em->getRepository('AppBundle:Friend')->findBy(array(
        'user_one' => ($user->getId()),
        'enabled' => 1
    ));
    $friend_4 = $em->getRepository('AppBundle:Friend')->findBy(array(
        'user_two' => ($user->getId()),
        'enabled' => 1
    ));
    $friend_1 = $em->getRepository('AppBundle:Friend')->findBy(array(
        'user_one' => ($user->getId()),
        'enabled' => 2
    ));
    $friend_2 = $em->getRepository('AppBundle:Friend')->findBy(array(
        'user_two' => ($user->getid()),
        'enabled' => 2
    ));

    if (!isset($friend_1) and !isset($friend_2)) {
        return new JsonResponse([
            'success' => "true",
            'message' => "Liste du Profil",
            'id' => $user->getId(),
            'username' => $user->getUsername(),
            'phone' => $profile->getPhone(),
            'email' => $profile->getEmail(),
            'resume' => $profile->getResume(),
            'language' => $profile->getLanguage(),
        ]);
    }

    $arrayCollection_1 = array();
    $arrayCollection_2 = array();
    $arrayCollection_3 = array();
    $arrayCollection_4 = array();


    foreach($friend_1 as $friends_1) {
        $arrayCollection_1[] = array(
            'id_friend' => $friends_1->getUserOne(),
        );
    }
    foreach($friend_2 as $friends_2) {
        $arrayCollection_2[] = array(
            'id_friend' => $friends_2->getUserOne(),
        );
    }
    foreach($friend_3 as $friends_3) {
        $arrayCollection_3[] = array(
            'id_friend' => $friends_3->getUserOne(),
        );
    }
    foreach($friend_4 as $friends_4) {
        $arrayCollection_4[] = array(
            'id_friend' => $friends_4->getUserOne(),
        );
    }

    return new JsonResponse([
        'success' => "true",
        'message' => "Liste du Profil",
        'id' => $user->getId(),
        'username' => $user->getUsername(),
        'phone' => $profile->getPhone(),
        'email' => $profile->getEmail(),
        'resume' => $profile->getResume(),
        'language' => $profile->getLanguage(),
        'friends_added' => $arrayCollection_1,
        'friends_accepted' => $arrayCollection_2,
        'friends_added_need_to_be_accept' => $arrayCollection_3,
        'friends_need_to_be_accept' => $arrayCollection_4,

    ]);
}

我的个人资料实体:

class Profile
{
/**
 * @var integer
 *
 * @ORM\Column(name="id", type="integer", nullable=false)
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="IDENTITY")
 * @ORM\OneToOne(targetEntity="User", inversedBy="Profile")
 */
protected $id;

/**
 * @var string
 *
 * @ORM\Column(name="resume", type="text", length=65535, nullable=true)
 */
protected $resume;

/**
 * @var string
 *
 * @Assert\Image()
 * @ORM\Column(name="avatar_path", type="string", length=255, nullable=true)
 */
protected $avatarPath;

/**
 * @var \DateTime
 *
 * @ORM\Column(name="last_connexion", type="datetime", nullable=false)
 */
protected $lastConnexion;

/**
 * @var \DateTime
 *
 * @ORM\Column(name="birth", type="datetime", nullable=false)
 */
protected $birth;

/**
 * @var string
 *
 * @ORM\Column(name="email", type="string", length=255, nullable=false, unique=true)
 */
protected $email;

/**
 * @var integer
 *
 * @ORM\Column(name="level", type="integer", nullable=false)
 */
protected $level = '1';

/**
 * @var string
 *
 * @ORM\Column(name="phone", type="string", length=60, nullable=true, unique=true)
 * @Assert\Regex(
 *     pattern="/(0|\+)[1-9]([-. ]?[0-9]{2}){4}/",
 *     message="You need to put a french number ! Starting with 0 or +33 !",
 * )
 */
protected $phone;

/**
 * @var string
 *
 * @ORM\Column(name="language", type="text", length=65535, nullable=true)
 */
protected $language;

/**
 * @var boolean
 *
 * @ORM\Column(name="is_male", type="boolean", nullable=false)
 */
protected $isMale = '1';

/**
 * @var \DateTime
 *
 * @ORM\Column(name="created_account", type="datetime", nullable=false)
 */
protected $createdAccount = 'CURRENT_TIMESTAMP';

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

/**
 * @param int $id
 */
public function setId($id)
{
    $this->id = $id;
}

/**
 * @return string
 */
public function getResume()
{
    return $this->resume;
}

/**
 * @param string $resume
 */
public function setResume($resume)
{
    $this->resume = $resume;
}

/**
 * @return string
 */
public function getAvatarPath()
{
    return $this->avatarPath;
}

/**
 * @param string|null
 */
public function setAvatarPath($avatarPath)
{
    $this->avatarPath = $avatarPath;
}

/**
 * @return \DateTime
 */
public function getLastConnexion()
{
    return $this->lastConnexion;
}

/**
 * @param \DateTime $lastConnexion
 */
public function setLastConnexion(\DateTime $lastConnexion)
{
    $this->lastConnexion = $lastConnexion;
}

/**
 * @return \DateTime
 */
public function getBirth()
{
    return $this->birth;
}

/**
 * @param \DateTime $birth
 */
public function setBirth(\DateTime $birth)
{
    $this->birth = $birth;
}

/**
 * @return string
 */
public function getEmail()
{
    return $this->email;
}

/**
 * @param string $email
 */
public function setEmail($email)
{
    $this->email = $email;
}

/**
 * @return int
 */
public function getLevel()
{
    return $this->level;
}

/**
 * @param int $level
 */
public function setLevel($level)
{
    $this->level = $level;
}

/**
 * @return string
 */
public function getPhone()
{
    return $this->phone;
}

/**
 * @param string|null
 */
public function setPhone($phone)
{
    $this->phone = $phone;
}

/**
 * @return string
 */
public function getLanguage()
{
    return $this->language;
}

/**
 * @param string $language
 */
public function setLanguage($language)
{
    $this->language = $language;
}

/**
 * @return \DateTime
 */
public function getCreatedAccount()
{
    return $this->createdAccount;
}

/**
 * @param \DateTime $createdAccount
 */
public function setCreatedAccount(\DateTime $createdAccount)
{
    $this->createdAccount = $createdAccount;
}

/**
 * @return bool
 */
public function isMale()
{
    return $this->isMale;
}

/**
 * @param bool $isMale
 */
public function setIsMale($isMale)
{
    $this->isMale = $isMale;
}
}

和我的朋友实体:

class Friend
{

/**
 * @var integer
 *
 * @ORM\Column(name="id", type="integer", nullable=false)
 * @ORM\Id()
 * @ORM\GeneratedValue(strategy="IDENTITY")
 */
protected $id;

/**
 * @var \AppBundle\Entity\User
 *
 * @ORM\GeneratedValue(strategy="NONE")
 * @ORM\ManyToOne(targetEntity="User")
 * @ORM\JoinColumns({
 *   @ORM\JoinColumn(name="user_id_one", referencedColumnName="id")
 * })
 */
protected $user_one;

/**
 * @var \AppBundle\Entity\User
 *
 * @ORM\GeneratedValue(strategy="NONE")
 * @ORM\ManyToOne(targetEntity="User")
 * @ORM\JoinColumns({
 *   @ORM\JoinColumn(name="user_id_two", referencedColumnName="id")
 * })
 */
protected $user_two;

/**
 * @var integer
 *
 * @ORM\Column(name="enabled", type="integer", nullable=false)
 */
private $enabled;

/**
 * @return int
 */
public function getEnabled()
{
    return $this->enabled;
}

/**
 * @param int $enabled
 */
public function setEnabled($enabled)
{
    $this->enabled = $enabled;
}

/**
 * @return User
 */
public function getUserTwo()
{
    return $this->user_two;
}

/**
 * @param User $user_two
 */
public function setUserTwo($user_two)
{
    $this->user_two = $user_two;
}

/**
 * @return User
 */
public function getUserOne()
{
    return $this->user_one;
}

/**
 * @param User $user_one
 */
public function setUserOne($user_one)
{
    $this->user_one = $user_one;
}

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

/**
 * @param int $id
 */
public function setId($id)
{
    $this->id = $id;
}

}

我100%确定我的实体很好,并且当我要填充数组时会出现错误。

看看我何时做:

foreach($friend_1 as $friends_1) {
    $arrayCollection_1[] = array(
        'id_friend' => 4,
    );
}

那让我回来了:

{
"success": "true",
"message": "Liste du Profil",
"id": 54,
"username": "TestTest7",
"phone": null,
"email": "noemail@gmail.com",
"resume": "TestTest7",
"language": null,
"friends_added": [
    {
        "id_friend": 4
    }
],
"friends_accepted": [],
"friends_added_need_to_be_accept": [],
"friends_need_to_be_accept": []
}

感谢任何试图回答并询问您是否想要我可能会忘记的细节的人!

1 个答案:

答案 0 :(得分:1)

在将要序列化并以json格式(例如User)发送的实体类上实施jsonSerialize。例子

class Friend implements JsonSerializable {
    // previous functions

    /**
     * Specify data which should be serialized to JSON
     * @link http://php.net/manual/en/jsonserializable.jsonserialize.php
     * @return mixed data which can be serialized by <b>json_encode</b>,
     * which is a value of any type other than a resource.
     * @since 5.4.0
     */
    function jsonSerialize()
    {
        return array(
            "id"       => $this->id,
            "enabled"  => $this->enabled,
            "user_one" => $this->user_one,
            "user_two" => $this->user_two,
        );
    }
}