我有一个对象 $myObject; 我试图将 php 对象作为 json 返回,但它丢失了一些数据。这是 $myObject 的样子:CreditOnline\Bundle\CreditOnlineBundle\PriceList\PriceList Object( [priceListId:CreditOnline\Bundle\CreditOnlineBundle\PriceList\PriceList:private] => 32 [amounts:CreditOnline\Bundle\CreditOnlineBundle\PriceList\PriceList:private] => Array ( [0] => 1000 [1] => 2000 [2] => 3000 [3] => 4000 [4] => 5000 [5] => 6000 [6] => 7000 ) [amountsKeys:CreditOnline\Bundle\CreditOnlineBundle\PriceList\PriceList:private] => Array ( [1000] => 0 [2000] => 1 [3000] => 2 [4000] => 3 [5000] => 4 [6000] => 5 [7000] => 6 ) [periods:CreditOnline\Bundle\CreditOnlineBundle\PriceList\PriceList:private] => Array ( [0] => 10 [1] => 15 [2] => 20 [3] => 25 [4] => 30 ) [periodsKeys:CreditOnline\Bundle\CreditOnlineBundle\PriceList\PriceList:private] => Array ( [10] => 0 [15] => 1 [20] => 2 [25] => 3 [30] => 4 ) [amount:CreditOnline\Bundle\CreditOnlineBundle\PriceList\PriceList:private] => 7000 [period:CreditOnline\Bundle\CreditOnlineBundle\PriceList\PriceList:private] => 30 [prices:CreditOnline\Bundle\CreditOnlineBundle\PriceList\PriceList:private] => Array ( ) )后 json_encode($myObject); 新数据看起来像这样(截图以获得更好的 json 视图):
1 回答
慕桂英3389331
TA贡献2036条经验 获得超8个赞
问题是json_encode
无法访问私有属性。
以下是您可以采取的一些解决方法:
将属性转换为公共
您可以在转换之前使用反射类来转换属性可访问性
例子:
$refObject = new ReflectionObject( $obj ); $refProperty = $refObject->getProperty( 'property' ); $refProperty->setAccessible( true );
您可以使用 Reflection 对象遍历对象的属性并调用所有 getter 将对象转换为可以轻松转换的数组结构
- 1 回答
- 0 关注
- 121 浏览
添加回答
举报
0/150
提交
取消