如何在 JSON Encode/Decode in PHP 之后维护对象状态

How to maintain object state after JSON Encode/Decode in PHP

下面的方法把对象中的属性实例变成了数组,但是要求不同,操作后响应的结果是一样的。

<?php

$data =  array('statusCode'=>200,
               'statusDescripion'=>'success',
               'data'=> array('companyImage'=>new StdClass(),
               'profile'=>array())
              );

echo "<br><br> Encoded data coming from API<br>";
echo $encodeData = json_encode($data,true);

//echo "<br><br> Decode data for Manipulation <br>";
$decodeData = json_decode($encodeData,true);
//print_r($decodeData);
if($decodeData['statusCode'] == 200){
    $data_ = array('statusCode'=>$decodeData['statusCode'],
                   'statusDescripion'=>$decodeData['statusDescripion'],
                   'data'=>$decodeData['data'],
                   'url'=>"php.com");
}

echo "<br><br> After Manipulation <br>";
echo json_encode($data_,true);

来自 json-decode 文档:

When TRUE, returned objects will be converted into associative arrays

您使用它以便将对象转换为数组 - 如果您希望它成为对象(又名 {}),只需从行中删除 true

$decodeData = json_decode($encodeData,true);

收件人:

$decodeData = json_decode($encodeData);

顺便说一句,json-encode 没有得到 true 作为第二个参数,我想你想要 JSON_FORCE_OBJECT