3

I have this class:

namespace backoffice\controller;

class MyObject{
   private $id;
   private $name;
}

I try to convert it to array and then json array:

$obj = new MyObject();
$obj->setId(1);
$obj->setName('Test');

json_encode((array)$obj);

I get this result:
{"backoffice\controller\MyObject\id":"1","backoffice\controller\MyObject\name":"Test"} !!!! EDIT:
Why I can't get this result:

{"id":"1","name":"Test"}
SlimenTN
  • 3,383
  • 7
  • 31
  • 78
  • What's your question ? – Daan Feb 11 '16 at 14:20
  • @Daan sorry, I edited the question, please take a look. – SlimenTN Feb 11 '16 at 14:22
  • because you're using a namespace... that's why. – Marc B Feb 11 '16 at 14:23
  • @MarcB so there is nothing I can do about it ? – SlimenTN Feb 11 '16 at 14:24
  • can't see any options in the docs to ignore/skip namespacing... and note that your `(array)` typecast is basically pointless. you're using string keys, which means you HAVE to use JS objects to store your data. arrays cannot have named keys. – Marc B Feb 11 '16 at 14:27
  • On a side note, the Json output you show cannot be correct because when you typecast private properties, the resulting array keys will have null bytes added to them. The more likely output is `{"\u0000backoffice\\controller\\MyObject\u0000id":1,"\u0000backoffice\\controller\\MyObject\u0000name":"Test"}` – Gordon Feb 11 '16 at 14:35

1 Answers1

3

Instead of converting it to array (which will do things you don't expect), have your MyObject implement the JsonSerializable interface.

namespace backoffice\controller;

class MyObject implements \JsonSerializable
{
   private $id;
   private $name;

   public function jsonSerialize() {
       return get_object_vars($this);
   }

   // setters
}

Then you can use json_encode on it directly and get the desired result:

$obj = new MyObject;
$obj->setId(1);
$obj->setName('foo');
echo json_encode($obj); // {"id":1,"name":"foo"}
Community
  • 1
  • 1
Gordon
  • 312,688
  • 75
  • 539
  • 559