I am using a PHP 5.6.40 development environment. Many of my classes implement JsonSerializable
. The jsonSerialize
method of one of these classes uses json_decode
, since the value of one of its data members may or may not be encoded as JSON. The problem is that after calling json_decode
on a data member whose value is just a plain string, the json_encode
fails.
Here is an example:
class JsonSerializableClass implements JsonSerializable
{
private $dataMember;
public function __construct($dataMember)
{
$this->dataMember = $dataMember;
}
public function jsonSerialize()
{
$decodedDataMember = json_decode($this->dataMember, 1);
if ($decodedDataMember && $decodedDataMember['jsonDataMember'])
{
return $decodedDataMember['jsonDataMember'];
}
// json_encode(''); This keeps json_encode from failing, but I'm looking for a different solution.
return $this->dataMember;
}
}
// This works
$test1 = new JsonSerializableClass(json_encode(array(
'jsonDataMember' => 'plain string'
)));
var_export(json_encode($test1));
// This fails
$test2 = new JsonSerializableClass('plain string');
var_export(json_encode($test2));
This is fixed by adding a call to json_encode
in the jsonSerialize method after the failed json_decode; however, another developer may not immediately realize what that accomplishes. Of course I would comment my reasoning for doing it, but I'm looking for a more clear solution. Is there error state data that json functions rely on that is being cleared by a successful json_encode
? If so, is there a way to clearly reset that error state data, like clear_json_error_state
?
I'm sorry if my explanation is hard to understand; it was difficult for me to explain. Please ask me for any clarification you need.