如何设置解码json的属性?

时间:2017-01-12 07:48:21

标签: php json yii yii1.x

我的控制器中有以下代码:

  public function loadJson($id)
    {
        $jsonfile=ChForms::model()->findByPk($id);
        $decodedJson=json_decode($jsonfile->json, true);
        return $decodedJson;
    }

  public function actionForms($id){
               $forms = ChForms::model()->findByPk($id);
              if ($forms->name == 'plaint') {
                $plaint = new PlaintForm();
                $models = $plaint;
                $filesname=CJSON::decode($forms->json)["ABlock"]["p_1"];
                $plaint_type=CJSON::decode($forms->json)["CBlock"]["p_1"];
                var_dump($this->loadJson($id));
                $models->setAttributes($this->loadJson($id), false);
                var_dump($models);
                $doc = $models->toWord($models, $plaint_type);
                header("Content-Transfer-Encoding: binary");
                header("Content-Disposition: attachment; filename=$filesname.docx");
                header("Content-Length: " . filesize($doc));
                header("Pragma: public"); // required
                header("Expires: 0");
                header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
                header("Cache-Control: private", false); // required for certain browsers
                //header("Content-Type:". $doc->mime_type);
                readfile($doc);
                unlink($doc);
                Yii::app()->end();
            }
        }

var_dump($this->loadJson($id));的结果是:

array(6) { ["ABlock"]=> array(36) { ["name"]=> string(6) "ablock" ["view"]=> string(10) "pdf/ablock" ["p_1"]=> string(12) "SSP 12345678"

的结果
 $models->setAttributes($this->loadJson($id), false);
                var_dump($models);

object(PlaintForm)#84 (11) { ["ABlock"]=> object(ABlockForm)#85 (43) { ["name"]=> string(6) "ablock" ["view"]=> string(10) "pdf/ablock" ["p_1"]=> NULL

$models->setAttributes($this->loadJson($id), false); 

未设置属性。我哪里弄错了?我该如何设置属性?

1 个答案:

答案 0 :(得分:0)

您可以使用以下PHP类将JSON映射到类。

https://github.com/cweiske/jsonmapper

$json     = json_decode(<JSON LOADED FROM ELSEWHERE>);
$mapper   = new JsonMapper();
$instance = $mapper->map($json, new <YOUR-CLASS>);