json_encode里面的json_encode结果

时间:2014-03-24 15:38:10

标签: php json

我需要你的帮助,我不能靠自己的帮助。 愿与我的差距。

我有两节课: 第一个(Application)有一个方法(toJson)将其私有变量作为json-string返回。

第二个(问题)包含第一个类,并且能够将其自己的内容及其子项的内容作为json返回。

现在,如果我调用高级第二类的toJson方法,此方法将调用其子级的toJson方法。

两个toJson方法都使用json_encode。 逻辑结果是,最终结果包含转义字符。

{"Application":"{\"Abbreviation\":\"GB\",\"Identifier\":1,\"Name\":\"Great Bounce"\"}"}

toJson-Application of Application类似于:

public function toJson()
{
    return json_encode(array(
        "Abbreviation" => $this->_Abbreviation,
        "Identifier" => $this->_Identifier->getId(),
        "Name" => $this->_Name
    ));
}

toJson-问题方法:

public function toJson()
{
    return json_encode(array(
        "Application" => $this->_Application->toJson();
    ));
}

转义字符会导致JavaScript出现问题。 有人会想到解决方案或不同的实现吗?

4 个答案:

答案 0 :(得分:3)

内部类实际返回的是一个字符串,而不是它自身的数组表示。所以外部类正在编码一个字符串;这个字符串包含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();
    ));
}

答案 1 :(得分:2)

这仍然允许您独立访问这些方法:

应用:

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();
    ));
}

答案 2 :(得分:2)

为了使其更灵活,我将在toArray和toJson上分隔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());
}

顺便说一句,将所有这些包装到接口中会很好。

答案 3 :(得分:0)

您可以解码数据,以获取一个对象,该对象将由json_encode再次编码:

public function toJson()
{
    return json_encode(array(
        "Application" => json_decode($this->_Application->toJson());
    ));
}

这样,您只能获得由_Application方法编码的toJSON属性。