Welcome Guest, Not a member yet? Register   Sign In
Serializing Doctrine objects to proper JSON content type using ResponseTrait
#1

(This post was last modified: 06-21-2022, 07:38 AM by b126.)

Dear all, 

I'm trying to return Doctrine serialized objects (thanks to JMS Serializer) as JSON.
I am extending the ResourceController (and then using ResponseTrait)

The problem is that the returned headers are of type "text/html" instead of "application/json" when i use Respond.
If I use the more classic Response->setJSON, then the header is fine.

If I well understand, Respond will always consider returning text/html when receiving a string as argument. 
How to get around this? 


PHP Code:
class Employees extends \CodeIgniter\RESTful\ResourceController
{
    public function index()
    {
        $serializer SerializerBuilder::create()->build();
        $res $serializer->serialize(getEmployeeRepo()->findAll(), 'json');

        //return $this->response->setJSON($res); //working well: application/json is returned
        return $this->respond($res); //faulty: text/html is returned
    }


Thank you
Reply
#2

Well, I think I get a workaround.

Using Serializer.toArray(); instead of Serializer.serialize(); will do the trick.
       

PHP Code:
$res $serializer->toArray(getEmployeeRepo()->findAll());
return 
$this->respond($res); //application/json is returned 
Reply
#3

$this->respond($res) sets the Content-Type: text/html header because $res is a string.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB