我有一个ResponseGrid
对象,我想在 Json 中对其进行编码。这个对象里面有一个$row
变量,它包含一个Document
个对象的数组。
我在JsonSerializable
和jsonSerialize()
中实施了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}}"}
为什么?我做错了吗?那些反斜杠是什么?