John Davidson

php - Convert type hinted php8 objects to json using json_encode

0 comments
Message:


I have the following code.


class SomeObject implements JsonSerializable {
public string $placeholder;
public string $id;
public string $model;
public string $value;
public bool $disabled;
public bool $required;

public function jsonSerialize()
{
return get_object_vars($this);
}
}

class MainObject implements JsonSerializable
{
public string $mainName;
public SomeObject $someObject;

public function __construct() {
$this->mainName = (new ReflectionClass(MainObject::class))->getShortName();
$this->someObject = new SomeObject();
}

public function jsonSerialize()
{
return get_object_vars($this);
}
}

$main = new MainObject;
$jsonData = json_encode($main, JSON_PRETTY_PRINT);

>>> Result:
{
"mainName": "MainObject",
"someObject": []
}

I would like the MainObject to look like this


{
"mainName": "MainObject",
"someObject": {
"placeholder": "",
"id": "",
"model": "",
"value": "",
"disabled": "",
"required": ""
}
}

however it seems that json_encode() method will only encode if objects have values assigned to them. if I make $someObject an associative array it works as expected.


How can I do this? Thanks in advance.



My Answer:
> public function jsonSerialize()
> {
> return [
> 'mainName' => $this->mainName,
> 'someObject' => $this->someObject
> ];
> }
> }

Now, when you call `json_encode` on an instance of `MainObject`, it will properly serialize the `SomeObject` property as well.

Rate this post

3 of 5 based on 4880 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us