PHP to JSON- How to serialize PHP class to JSON format?

If you are using PHP to implement REST API, you will come across this question. The answer to this, in general, is really simple.
PHP comes with two functions json_encode and json_decode, for encoding a PHP object into JSON and JSON string into PHP object respectively.
Check out the manual at Php.Net for the full details of this function.
The call is simple $j = json_encode($v);
$j contains the JSON for $v which can be an array, object or scalar variable.
However, here are a few limitations to json_encode.

  1. If you have strings stored in the object your encoding, they have to be UTF-8 strings or you need to convert them to UTF-8 using utf8_encode before calling json_encode
  2. If you have member variables that are marked as private, json_encode can’t see them.
  3. Associative arrays will be represented as objects. Sequential arrays will be represented as arrays in JSON. You can force them to be represented as objects by either casting the variable to object or pass in the option JSON_FORCEOBJECT

Being able to expose private and protected variables is very important. This can be done in various ways. You can use an Iterator like an ArrayIterator and call json_encode on that. The solution I am going to outline involves writing your own custom encode function that uses json_encode.
As an example you take the following classes in PHP. JsonTest contains JSon_Test1 which in turn contains JSonTest_2.

class Marshall
{

public function propvalues()
{

return get_object_vars($this);

}

}

class JSonTest_2 extends Marshall
{

public $arr2;
public function __construct()
{

$this->arr2 = array(1 => “stest”, 4 =>”stest2″, 3=>5.1);

}

}

class JSonTest_1 extends Marshall
{

public $arr1;
public $j2;
private $jp2;
public function __construct()
{

$this->arr1 = array(“test”, “test2”);
$this->j2 = new JSonTest_2();
$this->jp2 = “jp2”;

}
public function propvalues()
{

return array(“arr1” =>$this->arr1, “j2″=>$this->j2->propvalues(), “jp2″=>$this->jp2);

}

}

class JsonTest extends Marshall
{

private $arrActuary = array();
public $jt1;
private $jt11;
private $arrTestM = array();
public function __construct()
{

$this->jt1 = new JSonTest_1();
$this->jt11 = new JSonTest_1();
$this->arrTestM = array(1 =>”value”, “test” =>100.21);

}
public function propvalues()
{

return array(“jt1″=>$this->jt1->propvalues(), “jt11″=>$this->jt11->propvalues(), “arrTestM”=>$this->arrTestM);

}

}

class JSon
{

static public function encode($o)
{

if(is_a($o, “Marshall”))
return json_encode($o->propvalues());
return json_encode($o);

}

}

The following code will call normal json_encode passing in $j and then call the special encode on $j.
$j = new JsonTest();
echo “normal encode”;
echo json_encode($j);
echo “special encode”;
echo JSon::encode($j);
This will echo the following two lines: (You can pretty print these to make them more readable etc.)
normal encode
{“jt1”:{“arr1”:[“test”,”test2″],”j2″:{“arr2”:{“1″:”stest”,”4″:”stest2″,”3″:5.1}}}}
special encode
{“jt1”:{“arr1”:[“test”,”test2″],”j2″:{“arr2”:{“1″:”stest”,”4″:”stest2″,”3″:5.1}},”jp2″:”jp2″},”jt11″:{“arr1”:[“test”,”test2″],”j2″:{“arr2”:{“1″:”stest”,”4″:”stest2″,”3″:5.1}},”jp2″:”jp2″},”arrTestM”:{“1″:”value”,”test”:100.21}}

I define a class called Marshall which when inherited automatically exposes all the public variables as an array. If you override the function propvalues in the inherited class as is done in the class JSonTest_1, you will be able to iterate over the private and protected variables too.
I also defined a helper class JSon with static function encode which calls json_encode on the object if it does not inherit from Marshall otherwise it will call propvalues function and json_encode the return value.

Here we make use of two properties of json_encode to achieve this. First one is the fact that json_encode recursively encodes the objects. Second one is that associative arrays are encoded as objects. The second property is the one that’s used in propvalues where we are constructing the associative array with the private, protected and public variables.

Note that propvalues itself can check if the contained class in this case JSonTest_2 is a Marshall class and call propvalues on it.

The code above has an advantage over normal json_encode function in that you can transform the class to be different from what it is in PHP when you serialize in JSON.. can be selective about which member variables in the class you want to add to JSON. You can also decide what to name them.

(Note – json_encode is available in 5.2 version or later and get_object_vars in PHP version 4.0 or later)

2 thoughts on “PHP to JSON- How to serialize PHP class to JSON format?

  1. Hello There. I found your blog using msn. This is a very well written article.
    I will be sure to bookmark it and come back to read more of your useful info.
    Thanks for the post. I will certainly comeback.

Leave a comment