PHP JsonSerializable接口和带有嵌套对象的jsonSerialize

时间:2014-01-26 14:32:35

标签: php arrays json serialization

我有一个ResponseGrid对象,我想在 Json 中对其进行编码。这个对象里面有一个$row变量,它包含一个Document个对象的数组。

我在JsonSerializablejsonSerialize()中实施了ResponseGrid界面和Document方法。

我得到的是:

ResponseGrid.php:

require_once ROOT_DIR . "/business/models/Document.php";

class ResponseGrid implements JsonSerializable {

    private $sEcho;
    private $iTotalRecords;
    private $iTotalDisplayRecords;
    private $rows; // This will contain an Array of Documents

    public function jsonSerialize() {
        return [
            'sEcho' => $this->sEcho,
            'iTotalRecords' => $this->iTotalRecords,
            'iTotalDisplayRecords' => $this->iTotalDisplayRecords,
            'rows' => json_encode($this->rows), //This will cause troubles
        ];
    }
}

Document.php:

class Document implements JsonSerializable {

    private $id;
    private $name;
    private $description;
    private $contentId;

    public function jsonSerialize() {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'description' => $this->description,
            'contentId' => $this->contentId, 
        ];
    }
}

如果我在ResponseGrid数组中对填充了两个文档的$row对象进行回声,我会得到这个

echo json_encode($responseGrid);

{"sEcho":1,"iTotalRecords":27,"iTotalDisplayRecords":4,"rows":"{\"1\":{\"id\":1,\"name\":\"Greece\",\"description\":\"descGreece\",\"contentId\":2},\"2\":{\"id\":2,\"name\":\"Rome\",\"description\":\"descRome\",\"contentId\":3}}"}

为什么?我做错了吗?那些反斜杠是什么?

0 个答案:

没有答案