duandao8607 2018-07-31 07:29
浏览 109
已采纳

Symfony 3.4 - 返回数组JsonResponse

My question is simple I want to return an array for an api rest in json (with JsonResponse) :

I give you an exemple of what I started to do :

My json response :

{
  "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": []
}

As you can see, that's not what I want because the fields are empty : id_friend as content in database friends_added_need_to_be_accept too but the 2 others have empty database.

My controller :

/**
 *
 * @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,

    ]);
}

My profile entity :

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;
}
}

and my friend entity :

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;
}

}

I am 100% sure that my entities are good and that the error come when I want to fill the array.

Look when I do :

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

That return me :

{
"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": []
}

Thx for anyone who will try to answer and ask if you want more detail of something that I could forget !

  • 写回答

1条回答 默认 最新

  • dongzhuo2371 2018-07-31 08:01
    关注

    Implement jsonSerialize on entity classes that are going to be serialized and sent in json format like User. Example

    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,
            );
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何构建全国统一的物流管理平台?
  • ¥100 ijkplayer使用AndroidStudio/CMake编译,如何支持 rtsp 直播流?
  • ¥20 和学习数据的传参方式,选择正确的传参方式有关
  • ¥15 这是网络安全里面的poem code
  • ¥15 用js遍历数据并对非空元素添加css样式
  • ¥15 使用autodl云训练,希望有直接运行的代码(关键词-数据集)
  • ¥50 python写segy数据出错
  • ¥20 关于线性结构的问题:希望能从头到尾完整地帮我改一下,困扰我很久了
  • ¥30 3D多模态医疗数据集-视觉问答
  • ¥20 设计一个二极管稳压值检测电路