PHP jsonSerialize接口和jsonSerialize与嵌套对象
我有一个PHP jsonSerialize接口和jsonSerialize与嵌套对象,php,arrays,json,serialization,Php,Arrays,Json,Serialization,我有一个ResponseGrid对象,我想用Json对它进行编码。此对象内部有一个$row变量,该变量将包含一个文档对象数组 我在ResponseGrid和Document中实现了JsonSerializable接口和jsonSerialize()方法 我得到的是: ResponseGrid.php: require_once ROOT_DIR . "/business/models/Document.php"; class ResponseGrid implements JsonSerial
ResponseGrid
对象,我想用Json对它进行编码。此对象内部有一个$row
变量,该变量将包含一个文档
对象数组
我在ResponseGrid
和Document
中实现了JsonSerializable
接口和jsonSerialize()
方法
我得到的是:
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
];
}
}
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,
];
}
}
Document.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
];
}
}
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,
];
}
}
如果我对$row
数组中填充了两个文档的ResponseGrid
对象进行回显,我会得到以下结果
echo json_encode($responseGrid)代码>
为什么呢?我做错了吗?所有这些反斜杠是什么?在对象再次进行json编码之前,您正在对其进行json编码。您只需将行添加到ResponseGrid对象中,无需对其进行编码。您看到的是表示文档的转义字符串object@PatrickEvans你说得对:我在'rows'=>$this->rows
中更改了'rows'=>json\u编码($this->rows)
,现在一切都正常了。非常感谢。如果你把它写在回信里,我会接受的:)