所以我有以下内容,似乎无法将其转换为正常的JSON格式,我在FOSRestBundle中使用JMS序列化器的api。
发送到JMS序列化器的行是
return array(
'fields' => $entities,
);
$entities包含了下面所有的信息,下面你看到的是一个
print_r($entities);
输出:Array
(
[0] => Test'ClientBundle'Entity'Fieldset Object
(
[fieldid:Test'ClientBundle'Entity'Fieldset:private] => 43
[title:Test'ClientBundle'Entity'Fieldset:private] => Genre
[formid:Test'ClientBundle'Entity'Fieldset:private] => 1
[choicestext:Test'ClientBundle'Entity'Fieldset:private] => Array
(
[0] => stdClass Object
(
[label] => Folk
)
)
[defaultval:Test'ClientBundle'Entity'Fieldset:private] => 0
)
)
当我使用内置的JMS序列化器时,我得到这个:
{"fields":[{"fieldid":43,"title":"Genre","choicestext":"Array","defaultval":"0"}]
问题是,choicestext没有嵌套的JSON对象,但只是一个字符串"数组",我怎么能让代码插入它,所以它可以作为嵌套的JSON对象读取,有一个技巧与JMS序列化器?
这是插入到对象属性choicestext:
中的实际数组Array
(
[0] => stdClass Object
(
[label] => Folk
)
)
当使用json_encode作为JSON打印时,输出结果为:
[{"label":"Folk"}]
所以这是正确的,只是不明白为什么当插入实体时它不起作用?
更新:print_r(json_encode($entities));
结果:[{},{},{},{},{},{}]
考虑到choicestext字段被定义为字符串:
@ORM'Column(name="ChoicesText", type="string", length=255, nullable=false)
序列化程序使用实体元数据确定字段的数据类型。因为它认为字段包含字符串,所以它只是将当前值强制转换为字符串。如果您希望choicestext是一个字符串,不要将其设置为数组值。
首先将$entities转换为数组结构。这可以通过我写的这个函数来完成:
/**
* transforms any object into a array structure
*
* @param Object $object
* @return array
*/
protected function _objectToArray($object)
{
$array = array();
foreach ((array) $object as $key => $value) {
// is the value a object? transform it to a array itself
if (is_object($value)) {
$array[$key] = $this->_objectToArray($value);
} else {
$array[$key] = $value;
}
}
return $array;
}
,然后将其转换为json字符串。如果存在带有不同类型元素(数组,对象等)的多个关卡,则可能会出现结构奇怪的情况。但是,您总是可以使用标准的PHP数组函数来轻松地提取所需的信息。