New in Symfony 4.3: JSON validation
February 13, 2019 • Published by Javier Eguiluz
Warning: This post is about an unsupported Symfony version. Some of this information may be out of date. Read the most recent Symfony Docs.
Contributed by
Imad Zairig
in #28477.
JSON is arguably the most used format in applications developed with Symfony. You probably make requests to JSON APIs and send/receive JSON payloads in your projects. That's why Symfony provides a JsonResponse class, a way to build JSON authentication, full JSON support in the Serializer component, a json() helper for controllers, etc.
In Symfony 4.3 we improved the Validator component to add a new Json constraint, which can be applied to properties and getters, and ensures that the given contents are valid JSON contents:
- Annotations
- YAML
- XML
- PHP
1 2 3 4 5 6 7 8 9 10 11 12
// src/Entity/Book.php
namespace App\Entity;
use Symfony\Component\Validator\Constraints as Assert;
class Book
{
/**
* @Assert\Json(message = "This is not valid JSON")
*/
protected $chapters;
}
1 2 3 4 5 6
# config/validator/validation.yaml
App\Entity\Book:
properties:
chapters:
- Json:
message: 'This is not valid JSON'
1 2 3 4 5 6 7 8 9 10 11 12 13
<!-- config/validator/validation.xml -->
<?xml version="1.0" encoding="UTF-8" ?>
<constraint-mapping xmlns="http://symfony.com/schema/dic/constraint-mapping"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/constraint-mapping http://symfony.com/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd">
<class name="App\Entity\Book">
<property name="chapters">
<constraint name="Json">
<option name="message">This is not valid JSON</option>
</constraint>
</property>
</class>
</constraint-mapping>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// src/Entity/Book.php
namespace App\Entity;
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Constraints as Assert;
class Book
{
protected $chapters;
public static function loadValidatorMetadata(ClassMetadata $metadata)
{
$metadata->addPropertyConstraint('chapters', new Assert\Json(array(
'message' => 'This is not valid JSON',
)));
}
}
Help the Symfony project!
As with any Open-Source project, contributing code or documentation is the most common way to help, but we also have a wide range of sponsoring opportunities.
Comments are closed.
To ensure that comments stay relevant, they are closed for old posts.
example:
```php
public function confirmEmail(Request $request): JsonResponse
{
$token = \json_decode($request->getContent(), true)['token'] ?? null;
return $this->json($token);
}
```
vs
```php
public function confirmEmail(Request $request): JsonResponse
{
// json/getJson... etc.
$token = $request->jsonBody()->get('token');
return $this->json($token);
}
```