So i have created a few products and added some data to it:
In my custom route i am then trying to get all products out using the following code:
$products = \Drupal\commerce_product\Entity\Product::loadMultiple(); $response['data'] = $products; $response['method'] = 'GET'; return new JsonResponse($response);
However this returns the following reponse:
Can anyone tell me what ive done wrong?
The JSON response is not encoding past the first level of depth. As far as I can tell, you cannot control that when using
One solution is to build your own data structure and encode the JSON manually. This solution uses the serializer service: https://drupal.stackexchange.com/a/191474/70331
In your case, something like this should encode the full entity structure.
use Drupal\commerce_product\Entity\Product; use Symfony\Component\HttpFoundation\JsonResponse; ... $products = Product::loadMultiple([$ids]); $response['data'] = $products; $response['method'] = 'GET'; $serializer = \Drupal::service('serializer'); $jsonResponse = JsonResponse::fromJsonString($serializer->serialize($response, 'json')); return $jsonResponse;
If using the ‘serializer’ it is best to provide that to the controller via dependency injection.