apiobjectrequestsymfony4jsonresponse

Symfony 4 - JsonResponse returns a non-empty object as empty


I'm trying to return the result of an API request (using Postman) in Symfony.

Here is my relevant controller code:

/**
 * @Route("/apis/login", name="api_login")
 */
public function login(Request $request, UserRepository $userRepository): Response
{
    $cin = json_decode($request->getContent(),true)["cin"];
    $password = json_decode($request->getContent(),true)["password"];
    $user = $userRepository->findOneBy(['cin'=>$cin, 'password'=>$password]);
    if($user!=null){
        return new JsonResponse(json_encode($user));
    }else{
        return new JsonResponse("false");
    }
}

And this is the request body:

enter image description here

However, this is what I get as a result:

enter image description here

In my code, if I change this line return new JsonResponse(json_encode($user)); to this one return new JsonResponse(serialize($user)); , I get this:

enter image description here

Which proves that the returned object is not empty. Any idea how to fix that?


Solution

  • I've fixed it! I've just converted the user object to an array. So, I've changed my code like so:

     /**
     * @Route("/apis/login", name="api_login")
     */
    public function login(Request $request, UserRepository $userRepository): Response
    {
        $cin = json_decode($request->getContent(),true)["cin"];
        $password = json_decode($request->getContent(),true)["password"];
        $user = $userRepository->findOneBy(['cin'=>$cin, 'password'=>$password]);
        if($user!=null){
            $arr = (array) $user;
            foreach($arr as $k=>$v){
                $newkey = substr($k,17);
                $arr[$newkey] = $arr[$k];
                unset($arr[$k]);
            }
            return new JsonResponse($arr);
        }else{
            return new JsonResponse("false");
        }
    }