我需要你的帮助,我一个人做不到。愿你和我的差距。
我有两个类:第一个类(应用程序)有一个方法(toJson)将其私有变量返回为json。
第二个(问题)包含第一个类,并且能够将自己的内容和子类的内容作为json返回。
现在,如果我调用高级二等的toJson-方法,这个方法调用它的子类的toJson-方法。
两个toJson-方法都使用json_encode。逻辑结果是,最终结果包含转义字符.
{"Application":"{\"Abbreviation\":\"GB\",\"Identifier\":1,\"Name\":\"Great Bounce"\"}"}toJson-方法与以下类似:
public function toJson()
{
return json_encode(array(
"Abbreviation" => $this->_Abbreviation,
"Identifier" => $this->_Identifier->getId(),
"Name" => $this->_Name
));
}问题的处理方法:
public function toJson()
{
return json_encode(array(
"Application" => $this->_Application->toJson();
));
}转义字符导致了JavaScript的问题。有人会想到一个解决方案或不同的实现吗?
发布于 2014-03-24 15:43:34
内部类真正返回的是一个字符串,而不是其本身的数组表示。因此,外部类正在编码一个字符串;这个字符串包含JSON数据,这几乎是不相关的。我建议内部类除了JSON表示外,还应该有一个方法将自己作为数组表示返回:
public function toJson() {
return json_encode($this->toArray());
}
public function toArray() {
return array(
"Abbreviation" => $this->_Abbreviation,
"Identifier" => $this->_Identifier->getId(),
"Name" => $this->_Name
)
}然后,外部类接受以下数组表示:
public function toJson() {
return json_encode(array(
"Application" => $this->_Application->toArray();
));
}发布于 2014-03-24 15:43:27
这仍然允许您独立地访问这些方法:
应用程序:
public function toJson()
{
return json_encode($this->toArray());
}
public function toArray()
{
return array(
"Abbreviation" => $this->_Abbreviation,
"Identifier" => $this->_Identifier->getId(),
"Name" => $this->_Name
);
}问题:
public function toJson()
{
return json_encode(array(
"Application" => $this->_Application->toArray();
));
}发布于 2014-03-24 15:44:50
为了使它更加灵活,我将toJson方法分别放在toArray和toJson上:
申请课程:
public function toArray() {
return array(
"Abbreviation" => $this->_Abbreviation,
"Identifier" => $this->_Identifier->getId(),
"Name" => $this->_Name
);
}
public function toJson() {
return json_encode($this->toArray());
}问题课:
public function toArray() {
return array(
"Application" => $this->_Application->toArray();
);
}
public function toJson() {
return json_encode($this->toArray());
}顺便说一句,将所有这些都封装到接口中是很好的。
https://stackoverflow.com/questions/22613916
复制相似问题