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

Kur*_*aki 5 php arrays serialization json

我有一个ResponseGrid对象,我想用Json对其进行编码。这个对象内部有一个$row变量,它将包含一个Document对象数组。

我在和中都实现了JsonSerializable接口和jsonSerialize()方法。ResponseGridDocument

我有的是这样的:

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
        ];
    }
}
Run Code Online (Sandbox Code Playgroud)

文件.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, 
        ];
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我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}}"}
Run Code Online (Sandbox Code Playgroud)

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