How to work with JSON in Request Object

Hi,

I don’t understand, how I have to deal with JSON in a Request Object?
Adding a middleware as described in http://www.slimframework.com/docs/v4/objects/request.html#the-request-body does not work for me:

    class JsonBodyParser implements MiddlewareInterface
    {

    public function process(Request $request, RequestHandler $handler): Response
    {

        $contentType = $request->getHeaderLine('Content-Type');

        if (strstr($contentType, 'application/json')) {
            $contents = json_decode(file_get_contents('php://input'), true);
            if (json_last_error() === JSON_ERROR_NONE) {
                $request = $request->withParsedBody($contents);
                // this request object contains an array in getParsedBody()
                print_r(['$request' => $request]);
            }
        }

        return $handler->handle($request);
    }

   }


    $app = AppFactory::create();
    $app->addBodyParsingMiddleware();
    $app->add(new JsonBodyParser());
    $app->post('/test/json', function(Request $request, Response $response) {
         $response->getBody()->write(print_r([
            '$_POST' => $_POST,
            'getHeader(\'content-type\')' => $request->getHeader('content-type'),
            'getMethod()' => $request->getMethod(),
            'getParsedBody()' => $request->getParsedBody(), // empty 
            'getBody()' => $request->getBody()
        ], true));
    });

curl --header "Content-Type: application/json" --request POST --data '{"name":"xyz"}' http://127.0.0.1/test/json
1 Like

Hi!

You don’t need a custom JsonBodyParser, because you can use the PSR-7 Request object’s getParsedBody() method the get the JSON data as array.

$data = (array)$request->getParsedBody();

Hi,

thanks, this I tried at first. But it won’t work.

What OS do you use?
Have you tried the same test with Postman?

I am using docker-compose with two containers: PHP 7.4-fpm and nginx. I tried with postman and cUrl.

But…it seems that something else was strange. So I reinstalled all packages by composer and now it works!

Thank’s a lot for your quick help and answers!