We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Setting JsonContent outputs bools as 0/1

I'm working on a simple RESTful API and have a basic model. The model has a field which is being cast to bool through a getter.

On output of controller if I do return json_encode(["asdf"=>$alert->is_seen]); I see asdf:false, however if I do: $this->response->setJsonContent($alert); I get is_seen: 0. Why is there this inconsistency?

I've had to add an afterFetch method to cast the values returned from the db, which seems double the work - is this really the correct way?

Try something like this:


public function MyApiAction()
  {
    $this->response->setContentType("application/json");

    return $this->response->setJsonContent([
        "results" => $alert->is_seen
    ]);

    $this->response->send();
    $this->view->setRenderLevel(View::LEVEL_ACTION_VIEW);
  }
edited Jul '17

You're not using Micro but full MVC app? what happens if you return from your controller:

return $this->response->setJsonContent(['yourDataArray' => 0xff], JSON_NUMERIC_CHECK);

@Jonathan interesting - the bools are being output as 0/1.

I've since set a metadata strategy of annotation, and set the type for the boolean columns to 'boolean' in the annotations. shouldn't phalcon automatically cast them to bool?



10.4k
Accepted
answer

I think I solved it like this:

\Phalcon\Mvc\Model::setup([
    'castOnHydrate'      => true,
    'notNullValidations' => false,
]);