John Davidson

json - Laravel php multiple JsonSerializable

0 comments
Message:


I have complex object Model, with composition of other objects, and I use JsonSerializable in each of them.
Let take simplified example:


class CarPark implements JsonSerializable
{
/** @var array|Car[] */
private array $cars;
...
public function jsonSerialize()
{
return [
"title" => "My cars",
"cars" => $this->cars
];
}
}

class Car implements JsonSerializable
{
private string $model;
private string $year;
...
public function jsonSerialize()
{
return [
"model" => $this->model,
"year" => $this->year,
"price" => $this->calculate()

];
}
private function calculate():string {
...
}
}


For API I just do return new JsonResponse($carPark); and get nice json.
I want to save this object in DB as json, but I dont want to save 'price' value.


My question is:
How to make my object for API pass one json structure and for db another json structure?


P.S. For Laravel DB ORM I use Doctrine.



My Answer:
'cars' => $this->cars, ]; }}

class Car implements JsonSerializable{
/** @var string */
private string $brand;
/** @var string */
private string $model;

public function jsonSerialize()
{
return [
'brand' => $this->brand,
'model' => $this->model,
];
}
}

In this example, the CarPark class has an array of Car objects. Each Car object implements the JsonSerializable interface to customize how it is serialized to JSON. When you serialize a CarPark object, it will also serialize the array of Car objects inside it according to the jsonSerialize method defined in the Car class.

Rate this post

5 of 5 based on 9255 votes

Comments




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