Closed niqingyang closed 8 months ago
Json::encode()
supports JsonSerializable
interface. Needs to add JsonSerializable
to the class interfaces.
class User implements ArrayableInterface, JsonSerializable
{
...
public function jsonSerialize(): mixed
{
return $this->toArray();
}
...
}
Json::encode()
supportsJsonSerializable
interface. Needs to addJsonSerializable
to the class interfaces.class User implements ArrayableInterface, JsonSerializable { ... public function jsonSerialize(): mixed { return $this->toArray(); } ... }
ok
Also we can add support ArrayableInterface
(yiisoft/arrays
will be optional dependency):
if ($data instanceof ArrayableInterface) {
return self::processArray($data->toArray());
}
Does that make sense? Are there any cases when object with ArrayableInterface
should be serialized to json in different way?
Does that make sense? Are there any cases when object with
ArrayableInterface
should be serialized to json in different way?
I'm for explicit conversion to json
using JsonSerializable::jsonSerialize()
.
For example, ActiveRecord
objects will be converted using ActiveRecord::getAttributes()
, but if to support ArrayableInterface
inside Json::encode()
the result will be different.
class Model extends ActiveRecord
{
...
public function fields(): array
{
return [
'firstName' => 'first_name',
'lastName' => 'last_name',
];
}
}
Result for current implementation
$json = Json::encode($model);
// {"first_name":"John","last_name":"Smith"}
Result if to support ArrayableInterface
$json = Json::encode($model);
// {"firstName":"John","lastName":"Smith"}
What steps will reproduce the problem?
Json::encode() did not handle the object of ArrayableInterface, like Yii2
What is the expected result?
What do you get instead?
Additional info